go-tower: added StaticFS and fixed buildFullPath: v0.1.1
This commit is contained in:
23
tower.go
23
tower.go
@@ -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...)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user