From b66d65578014da938503b146a21e0ccbece6acd0 Mon Sep 17 00:00:00 2001 From: Ada Date: Mon, 2 Oct 2023 19:22:56 +0200 Subject: [PATCH] change(backend): serve static file from /static and serve index.html for / --- config.go | 6 ++++++ go.mod | 6 ++++++ main.go | 27 +++++++++++++++++++-------- app.js => static/app.js | 0 index.html => static/index.html | 2 +- style.css => static/style.css | 0 6 files changed, 32 insertions(+), 9 deletions(-) rename app.js => static/app.js (100%) rename index.html => static/index.html (95%) rename style.css => static/style.css (100%) diff --git a/config.go b/config.go index e6eef3f..3126aeb 100644 --- a/config.go +++ b/config.go @@ -12,6 +12,7 @@ type config struct { redisUser string redisPassword string redisDB int + urlLength int } func setConfig() config { @@ -33,6 +34,10 @@ func setConfig() config { redisDB = 0 } + urlLength, err := strconv.Atoi("PLAKKEN_URL_LENGTH") + if err != nil { + urlLength = 3 + } s := config{ host: host, port: port, @@ -40,6 +45,7 @@ func setConfig() config { redisUser: redisUser, redisPassword: redisPassword, redisDB: redisDB, + urlLength: urlLength, } return s diff --git a/go.mod b/go.mod index 4a496c4..4996e79 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,9 @@ module plakken go 1.21 + +require ( + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/redis/go-redis/v9 v9.2.1 // indirect +) diff --git a/main.go b/main.go index 82b3630..627ed98 100644 --- a/main.go +++ b/main.go @@ -1,19 +1,30 @@ package main import ( - "fmt" "net/http" + "strings" ) +var currentConfig config + +func handleRequest(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + if path == "/" { + http.ServeFile(w, r, "./static/index.html") + + } else if strings.HasPrefix(path, "/static/") { + fs := http.FileServer(http.Dir("./static")) + http.Handle("/static/", http.StripPrefix("/static/", fs)) + } else { + w.WriteHeader(http.StatusNotFound) + } + +} + func main() { - currentConfig := setConfig() + currentConfig = setConfig() listen := currentConfig.host + ":" + currentConfig.port - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - _, err := fmt.Fprintf(w, "Hello, you're at %s", r.URL.Path) - if err != nil { - return - } - }) + http.HandleFunc("/", handleRequest) err := http.ListenAndServe(listen, nil) if err != nil { diff --git a/app.js b/static/app.js similarity index 100% rename from app.js rename to static/app.js diff --git a/index.html b/static/index.html similarity index 95% rename from index.html rename to static/index.html index cbf8e4f..50e672b 100644 --- a/index.html +++ b/static/index.html @@ -6,7 +6,7 @@ name="viewport"> Your plak • Plakken - + diff --git a/style.css b/static/style.css similarity index 100% rename from style.css rename to static/style.css