aboutsummaryrefslogtreecommitdiffstats
path: root/cmd/server
diff options
context:
space:
mode:
authorAlexander Rakoczy <[email protected]>2021-10-21 02:31:57 -0400
committerAlexander Rakoczy <[email protected]>2021-10-21 02:31:57 -0400
commit34fa0a9b4fd446b1a844020786a691fecc2f89d5 (patch)
treeadf5fdc681d19c622823e81fd4b243476a17677c /cmd/server
parente9f01464f011b4a49a99dc2e05a02a47b829408b (diff)
show a frog
Diffstat (limited to 'cmd/server')
-rw-r--r--cmd/server/main.go68
1 files changed, 66 insertions, 2 deletions
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)
+ })
}