add Basic-Auth example

This commit is contained in:
syumai 2022-05-20 00:28:02 +09:00
parent 831e8ffb73
commit 0ad2687f16
8 changed files with 89 additions and 0 deletions

1
examples/basic-auth-server/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
dist

View File

@ -0,0 +1,12 @@
.PHONY: dev
dev:
wrangler dev
.PHONY: build
build:
mkdir -p dist
tinygo build -o ./dist/app.wasm -target wasm ./...
.PHONY: publish
publish:
wrangler publish

View File

@ -0,0 +1,10 @@
# basic-auth-server
* This is an example of an HTTP server with Basic-Auth .
## Demo
* https://basic-auth-server.syumai.workers.dev/
userName: `user`
password: `password`

View File

@ -0,0 +1,7 @@
module github.com/syumai/basic-auth-server
go 1.18
require github.com/syumai/workers v0.0.0
replace github.com/syumai/workers => ../../

View File

@ -0,0 +1,2 @@
github.com/syumai/workers v0.1.0 h1:z5QfQR2X+PCKzom7RodpI5J4D5YF7NT7Qwzb9AM9dgY=
github.com/syumai/workers v0.1.0/go.mod h1:alXIDhTyeTwSzh0ZgQ3cb9HQPyyYfIejupE4Z3efr14=

View File

@ -0,0 +1,31 @@
package main
import (
"net/http"
"github.com/syumai/workers"
)
const (
userName = "user"
userPassword = "password"
)
func authenticate(req *http.Request) bool {
username, password, ok := req.BasicAuth()
return ok && username == userName && password == userPassword
}
func handleRequest(w http.ResponseWriter, req *http.Request) {
if !authenticate(req) {
w.Header().Add("WWW-Authenticate", `Basic realm="login is required"`)
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized\n"))
return
}
w.Write([]byte("Authorized!\n"))
}
func main() {
workers.Serve(http.HandlerFunc(handleRequest))
}

View File

@ -0,0 +1,17 @@
import "../assets/polyfill_performance.js";
import "../assets/wasm_exec.js";
import mod from "./dist/app.wasm";
const go = new Go();
const load = WebAssembly.instantiate(mod, go.importObject).then((instance) => {
go.run(instance);
return instance;
});
export default {
async fetch(req) {
await load;
return handleRequest(req);
},
};

View File

@ -0,0 +1,9 @@
name = "basic-auth-server"
main = "./worker.mjs"
compatibility_date = "2022-05-13"
compatibility_flags = [
"streams_enable_constructors"
]
[build]
command = "make build"