From e71729ab1fb1c5db769e6e91bbbeb65a2a09555b Mon Sep 17 00:00:00 2001 From: Timo Riegebauer Date: Sun, 15 Feb 2026 11:51:26 +0000 Subject: [PATCH] go-tower: added StaticFS to Group: v0.1.2 --- group.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/group.go b/group.go index c80e5b4..4d9835a 100644 --- a/group.go +++ b/group.go @@ -1,7 +1,11 @@ package tower import ( + "io/fs" "net/http" + "path" + + "github.com/julienschmidt/httprouter" ) 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)) } +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) { g.Handle(http.MethodGet, path, h, routeMiddlewares...) }