embed html template and static files

This commit is contained in:
ari melody 2025-09-30 19:03:35 +01:00
parent b150fa491c
commit e5dcc4b884
Signed by: ari
GPG key ID: CF99829C92678188
44 changed files with 316 additions and 255 deletions

View file

@ -1,13 +1,31 @@
package view
import (
"embed"
"errors"
"mime"
"net/http"
"os"
"path"
"path/filepath"
)
func StaticHandler(directory string) http.Handler {
func ServeEmbedFS(fs embed.FS, dir string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
file, err := fs.ReadFile(filepath.Join(dir, filepath.Clean(r.URL.Path)))
if err != nil {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", mime.TypeByExtension(path.Ext(r.URL.Path)))
w.WriteHeader(http.StatusOK)
w.Write(file)
})
}
func ServeFiles(directory string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
info, err := os.Stat(filepath.Join(directory, filepath.Clean(r.URL.Path)))
@ -28,4 +46,3 @@ func StaticHandler(directory string) http.Handler {
http.FileServer(http.Dir(directory)).ServeHTTP(w, r)
})
}

View file

@ -40,6 +40,6 @@ func IndexHandler(app *model.AppState) http.Handler {
return
}
StaticHandler("public").ServeHTTP(w, r)
ServeEmbedFS(app.PublicFS, "public").ServeHTTP(w, r)
})
}