From 34fa0a9b4fd446b1a844020786a691fecc2f89d5 Mon Sep 17 00:00:00 2001 From: Alexander Rakoczy Date: Thu, 21 Oct 2021 02:31:57 -0400 Subject: show a frog --- cmd/server/main.go | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 2 deletions(-) (limited to 'cmd/server') diff --git a/cmd/server/main.go b/cmd/server/main.go index 9111f5d..d00ea02 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -1,7 +1,71 @@ package main -import "fmt" +import ( + "context" + "io" + "io/fs" + "log" + "mime" + "net" + "net/http" + "os" + "path" + "strings" + + "cloud.google.com/go/storage" + "git.toothrot.net/i.dis.band/internal" +) func main() { - fmt.Println("Hello, world") + var host string + port := os.Getenv("PORT") + if port == "" { + host = "localhost" + port = "8080" + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + cl, err := storage.NewClient(ctx) + if err != nil { + log.Fatalf("storage.NewClient() = _, %v", err) + } + b := cl.Bucket("i.dis.band") + http.Handle("/", fileServerHandler(internal.Static, image(b, http.HandlerFunc(home)))) + log.Printf("Listening on %s\n", net.JoinHostPort(host, port)) + log.Fatal(http.ListenAndServe(net.JoinHostPort(host, port), nil)) +} + +func image(b *storage.BucketHandle, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/" { + next.ServeHTTP(w, r) + return + } + o, err := b.Object(strings.TrimPrefix(r.URL.Path, "/")).NewReader(r.Context()) + if err != nil { + log.Printf("b.Object(%q) = %v", r.URL.Path, err) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", mime.TypeByExtension(path.Ext(r.URL.Path))) + w.Header().Set("Cache-Control", "no-cache, private, max-age=0") + io.Copy(w, o) + }) +} + +func home(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("hello")) +} + +func fileServerHandler(fs fs.FS, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasPrefix(r.URL.Path, "/static") { + next.ServeHTTP(w, r) + return + } + w.Header().Set("Content-Type", mime.TypeByExtension(path.Ext(r.URL.Path))) + w.Header().Set("Cache-Control", "no-cache, private, max-age=0") + s := http.FileServer(http.FS(fs)) + s.ServeHTTP(w, r) + }) } -- cgit v1.2.3-73-g0e29