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 WORKDIR /app
COPY --from=builder /app/teafolio /app/teafolio COPY --from=builder /app/teafolio /app/teafolio
COPY /static /app/static
ENTRYPOINT [ "/app/teafolio" ] ENTRYPOINT [ "/app/teafolio" ]

View File

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