From 0fcdacfc691e17ca15dc7e0d48a439ef7a52d9c7 Mon Sep 17 00:00:00 2001 From: Anhgelus Morhtuuzh Date: Thu, 2 Oct 2025 16:29:20 +0200 Subject: feat(backend): handle static files --- backend/config.go | 3 +++ backend/router.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 backend/config.go (limited to 'backend') diff --git a/backend/config.go b/backend/config.go new file mode 100644 index 0000000..b7624fd --- /dev/null +++ b/backend/config.go @@ -0,0 +1,3 @@ +package backend + +type Config struct{} diff --git a/backend/router.go b/backend/router.go index 6c7f9f8..4c3b2f8 100644 --- a/backend/router.go +++ b/backend/router.go @@ -1,7 +1,10 @@ package backend import ( + "embed" + "io/fs" "net/http" + "strings" "time" "github.com/go-chi/chi/v5" @@ -22,3 +25,45 @@ func NewRouter() *chi.Mux { }) return r } + +// httpEmbedFS is an implementation of fs.FS, fs.ReadDirFS and fs.ReadFileFS helping to manage embed.FS for http server +type httpEmbedFS struct { + embed.FS + prefix string +} + +func (h *httpEmbedFS) Open(name string) (fs.File, error) { + return h.FS.Open(h.prefix + "/" + name) +} + +func (h *httpEmbedFS) ReadFile(name string) ([]byte, error) { + return h.FS.ReadFile(h.prefix + "/" + name) +} + +func (h *httpEmbedFS) ReadDir(name string) ([]fs.DirEntry, error) { + return h.FS.ReadDir(h.prefix + "/" + name) +} + +// UsableEmbedFS converts embed.FS into usable fs.FS by Golatt +// +// folder may not finish or start with a slash (/) +func UsableEmbedFS(folder string, em embed.FS) fs.FS { + return &httpEmbedFS{ + prefix: folder, + FS: em, + } +} + +func HandleStaticFiles(r *chi.Mux, path string, root fs.FS) { + if path != "/" && path[len(path)-1] != '/' { + r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP) + path += "/" + } + path += "*" + + r.Get(path, func(w http.ResponseWriter, r *http.Request) { + ctx := chi.RouteContext(r.Context()) + pathPrefix := strings.TrimSuffix(ctx.RoutePattern(), "/*") + http.StripPrefix(pathPrefix, http.FileServerFS(root)).ServeHTTP(w, r) + }) +} -- cgit v1.2.3