change(backend): serve static file from /static and serve index.html for /

This commit is contained in:
Ada 2023-10-02 19:22:56 +02:00
parent 0977e8d064
commit d6f90977e1
6 changed files with 32 additions and 9 deletions

View file

@ -12,6 +12,7 @@ type config struct {
redisUser string redisUser string
redisPassword string redisPassword string
redisDB int redisDB int
urlLength int
} }
func setConfig() config { func setConfig() config {
@ -33,6 +34,10 @@ func setConfig() config {
redisDB = 0 redisDB = 0
} }
urlLength, err := strconv.Atoi("PLAKKEN_URL_LENGTH")
if err != nil {
urlLength = 3
}
s := config{ s := config{
host: host, host: host,
port: port, port: port,
@ -40,6 +45,7 @@ func setConfig() config {
redisUser: redisUser, redisUser: redisUser,
redisPassword: redisPassword, redisPassword: redisPassword,
redisDB: redisDB, redisDB: redisDB,
urlLength: urlLength,
} }
return s return s

6
go.mod
View file

@ -1,3 +1,9 @@
module plakken module plakken
go 1.21 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
)

29
main.go
View file

@ -1,19 +1,30 @@
package main package main
import ( import (
"fmt"
"net/http" "net/http"
"strings"
) )
func main() { var currentConfig config
currentConfig := setConfig()
listen := currentConfig.host + ":" + currentConfig.port func handleRequest(w http.ResponseWriter, r *http.Request) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path
_, err := fmt.Fprintf(w, "Hello, you're at %s", r.URL.Path) if path == "/" {
if err != nil { http.ServeFile(w, r, "./static/index.html")
return
} 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()
listen := currentConfig.host + ":" + currentConfig.port
http.HandleFunc("/", handleRequest)
err := http.ListenAndServe(listen, nil) err := http.ListenAndServe(listen, nil)
if err != nil { if err != nil {

View file

@ -6,7 +6,7 @@
name="viewport"> name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible"> <meta content="ie=edge" http-equiv="X-UA-Compatible">
<title>Your plak • Plakken</title> <title>Your plak • Plakken</title>
<link href="style.css" rel="stylesheet"> <link href="/static/style.css" rel="stylesheet">
</head> </head>
<body> <body>
<label for="content"></label> <label for="content"></label>