1 Commits

Author SHA1 Message Date
e71729ab1f go-tower: added StaticFS to Group: v0.1.2 2026-02-15 11:51:26 +00:00

View File

@@ -1,7 +1,11 @@
package tower package tower
import ( import (
"io/fs"
"net/http" "net/http"
"path"
"github.com/julienschmidt/httprouter"
) )
type Group struct { type Group struct {
@@ -40,6 +44,27 @@ func (g *Group) Static(prefix, dir string) {
g.parent.router.ServeFiles(buildFullPath(g.prefix, prefix), http.Dir(dir)) g.parent.router.ServeFiles(buildFullPath(g.prefix, prefix), http.Dir(dir))
} }
func (g *Group) StaticFS(prefix string, fsys fs.FS) {
fileServer := http.FileServer(http.FS(fsys))
handler := func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
fp := p.ByName("filepath")
if fp == "" {
fp = "/"
}
fp = path.Clean("/" + fp)
req := r.Clone(r.Context())
req.URL.Path = fp
fileServer.ServeHTTP(w, req)
}
g.parent.router.Handle(http.MethodGet, buildFullPath(g.prefix, buildFullPath(prefix, "/*filepath")), handler)
g.parent.router.Handle(http.MethodHead, buildFullPath(g.prefix, buildFullPath(prefix, "/*filepath")), handler)
}
func (g *Group) GET(path string, h Handler, routeMiddlewares ...Middleware) { func (g *Group) GET(path string, h Handler, routeMiddlewares ...Middleware) {
g.Handle(http.MethodGet, path, h, routeMiddlewares...) g.Handle(http.MethodGet, path, h, routeMiddlewares...)
} }