diff options
| author | Anhgelus Morhtuuzh <william@herges.fr> | 2025-10-02 16:29:20 +0200 |
|---|---|---|
| committer | Anhgelus Morhtuuzh <william@herges.fr> | 2025-10-02 16:29:20 +0200 |
| commit | 0fcdacfc691e17ca15dc7e0d48a439ef7a52d9c7 (patch) | |
| tree | fdea74d44fca640cc3f5e6135e91ebf0ccbe38b8 /backend/router.go | |
| parent | 4cff7748af65038db3754ab9ce157d528f03a474 (diff) | |
feat(backend): handle static files
Diffstat (limited to 'backend/router.go')
| -rw-r--r-- | backend/router.go | 45 |
1 files changed, 45 insertions, 0 deletions
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) + }) +} |
