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

@@ -17,7 +17,7 @@ func (g *Group) Use(groupMiddlewares ...Middleware) {
func (g *Group) Group(prefix string, mws ...Middleware) *Group {
child := &Group{
parent: g.parent,
prefix: g.buildFullPath(prefix),
prefix: buildFullPath(g.prefix, prefix),
}
child.groupMiddlewares = make([]Middleware, 0, len(g.groupMiddlewares)+len(mws))
@@ -37,7 +37,7 @@ func (g *Group) Static(prefix, dir string) {
}
prefix += "/*filepath"
g.parent.router.ServeFiles(g.buildFullPath(prefix), http.Dir(dir))
g.parent.router.ServeFiles(buildFullPath(g.prefix, prefix), http.Dir(dir))
}
func (g *Group) GET(path string, h Handler, routeMiddlewares ...Middleware) {
@@ -61,7 +61,7 @@ func (g *Group) DELETE(path string, h Handler, routeMiddlewares ...Middleware) {
}
func (g *Group) Handle(method string, path string, h Handler, routeMiddlewares ...Middleware) {
fullPath := g.buildFullPath(path)
fullPath := buildFullPath(g.prefix, path)
mws := make([]Middleware, 0, len(g.groupMiddlewares)+len(routeMiddlewares))
mws = append(mws, g.groupMiddlewares...)
@@ -69,14 +69,3 @@ func (g *Group) Handle(method string, path string, h Handler, routeMiddlewares .
g.parent.Handle(method, fullPath, h, mws...)
}
func (g *Group) buildFullPath(path string) string {
normalizedPrefix := normalizePath(g.prefix)
normalizedPath := normalizePath(path)
if normalizedPrefix == "/" && normalizedPath == "/" {
return "/"
}
return normalizePath(g.prefix) + normalizePath(path)
}

19
path.go
View File

@@ -12,3 +12,22 @@ func normalizePath(path string) string {
return "/" + path
}
func buildFullPath(prefix string, path string) string {
normalizedPrefix := normalizePath(prefix)
normalizedPath := normalizePath(path)
if normalizedPrefix == "/" && normalizedPath == "/" {
return "/"
}
if normalizedPrefix == "/" {
return normalizedPath
}
if normalizedPath == "/" {
return normalizedPrefix
}
return normalizedPrefix + normalizedPath
}

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...)
}