package backend import ( "embed" "io/fs" "net/http" "strings" "time" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" ) //go:embed templates var templates embed.FS func NewRouter() *chi.Mux { r := chi.NewRouter() r.Use(middleware.Timeout(30 * time.Second)) r.Use(middleware.Logger) 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, req *http.Request) { ctx := chi.RouteContext(req.Context()) pathPrefix := strings.TrimSuffix(ctx.RoutePattern(), "/*") if pathPrefix+"/" == req.URL.Path { r.NotFoundHandler().ServeHTTP(w, req) return } http.StripPrefix(pathPrefix, http.FileServerFS(root)).ServeHTTP(w, req) }) }