go-tower: added StaticFS and fixed buildFullPath: v0.1.1

This commit is contained in:
2026-02-15 11:48:47 +00:00
parent 3576d420d2
commit c8718716b8
3 changed files with 45 additions and 14 deletions

View File

@@ -2,8 +2,10 @@ package tower
import (
"context"
"io/fs"
"log"
"net/http"
"path"
"github.com/julienschmidt/httprouter"
)
@@ -66,6 +68,27 @@ func (t *Tower) Static(prefix, dir string) {
t.router.ServeFiles(prefix, http.Dir(dir))
}
func (t *Tower) 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)
}
t.router.Handle(http.MethodGet, buildFullPath(prefix, "/*filepath"), handler)
t.router.Handle(http.MethodHead, buildFullPath(prefix, "/*filepath"), handler)
}
func (t *Tower) GET(path string, h Handler, routeMiddlewares ...Middleware) {
t.Handle(http.MethodGet, path, h, routeMiddlewares...)
}