use go1.16+ embed for static assets

This commit is contained in:
mappu 2024-03-19 18:42:02 +13:00
parent eda45221cd
commit 1b3a720323
2 changed files with 16 additions and 11 deletions

View File

@ -10,6 +10,5 @@ FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/teafolio /app/teafolio
COPY /static /app/static
ENTRYPOINT [ "/app/teafolio" ]

View File

@ -1,6 +1,7 @@
package main
import (
"embed"
"encoding/base64"
"fmt"
"net/http"
@ -8,6 +9,14 @@ import (
"strings"
)
//go:embed static/*
var StaticFiles embed.FS
func (this *Application) ServeStatic(w http.ResponseWriter, r *http.Request) {
http.FileServer(http.FS(StaticFiles)).ServeHTTP(w, r)
// http.StripPrefix(`/static/`, http.FileServer(http.FS(StaticFiles))).ServeHTTP(w, r)
}
func (this *Application) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == `GET` {
if r.URL.Path == `/` {
@ -56,8 +65,9 @@ func (this *Application) ServeHTTP(w http.ResponseWriter, r *http.Request) {
this.Repopage(w, r, repoName)
} else if r.URL.Path == `/static/logo.png` {
if this.cfg.Template.CustomLogoPngBase64 != "" {
} else if strings.HasPrefix(r.URL.Path, `/static/`) {
if r.URL.Path == `/static/logo.png` && this.cfg.Template.CustomLogoPngBase64 != "" {
logoPng, err := base64.StdEncoding.DecodeString(this.cfg.Template.CustomLogoPngBase64)
if err != nil {
@ -69,16 +79,12 @@ func (this *Application) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set(`Content-Type`, `image/png`)
w.WriteHeader(200)
w.Write(logoPng)
} else {
r.URL.Path = r.URL.Path[8:]
http.FileServer(http.Dir(`static`)).ServeHTTP(w, r)
return
}
} else if strings.HasPrefix(r.URL.Path, `/static/`) {
r.URL.Path = r.URL.Path[8:]
http.FileServer(http.Dir(`static`)).ServeHTTP(w, r)
// Embedded resource
// r.URL.Path = r.URL.Path[8:]
this.ServeStatic(w, r)
} else if r.URL.Query().Get("go-get") == "1" {
// This wasn't one of our standard `/repo` paths, but there is the ?go-get=1 parameter