From a8b59428334b9029f934f94e8bb4952fba48cca2 Mon Sep 17 00:00:00 2001 From: Bel LaPointe Date: Fri, 7 Apr 2023 12:03:33 -0600 Subject: [PATCH] http stub --- http.go | 43 +++++++++++++++++++++++++++++++++++++++++++ main.go | 8 ++++++++ 2 files changed, 51 insertions(+) create mode 100644 http.go diff --git a/http.go b/http.go new file mode 100644 index 0000000..596c4c7 --- /dev/null +++ b/http.go @@ -0,0 +1,43 @@ +package main + +import ( + "context" + "fmt" + "net/http" +) + +type Context struct { + User string +} + +func HTTP(port int, db DB) error { + foo := func(w http.ResponseWriter, r *http.Request) { + } + foo = withAuth(foo) + return http.ListenAndServe(fmt.Sprintf(":%d", port), http.HandlerFunc(foo)) +} + +func extract(ctx context.Context) Context { + v := ctx.Value("__context") + v2, _ := v.(Context) + return v2 +} + +func inject(ctx context.Context, v Context) context.Context { + return context.WithValue(ctx, "__context", v) +} + +func withAuth(foo http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + u, _, ok := r.BasicAuth() + if !ok || u == "" { + w.Header().Set("WWW-Authenticate", "Basic") + w.WriteHeader(401) + return + } + c := extract(r.Context()) + c.User = u + r = r.WithContext(inject(r.Context(), c)) + foo(w, r) + } +} diff --git a/main.go b/main.go index 3ad773d..0f89c83 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "bytes" "fmt" "os" + "strconv" "strings" "time" ) @@ -59,6 +60,13 @@ func Main() error { return err } defer db.Close() + if port, _ := strconv.Atoi(os.Getenv("PORT")); port > 0 { + return HTTP(port, db) + } + return Terminal(db) +} + +func Terminal(db DB) error { user := IDU(os.Getenv("USER")) failed, err := Review(db, user) if err != nil {