Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5dd67e22c2 | |||
| e71729ab1f |
25
group.go
25
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...)
|
||||
}
|
||||
|
||||
16
tower.go
16
tower.go
@@ -49,6 +49,22 @@ func (t *Tower) SetErrorHandler(errorHandler ErrorHandler) {
|
||||
t.errorHandler = errorHandler
|
||||
}
|
||||
|
||||
func (t *Tower) SetNotFoundHandler(notFoundHandler Handler) {
|
||||
t.router.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := Context{
|
||||
request: r,
|
||||
response: &responseWriter{ResponseWriter: w},
|
||||
params: httprouter.Params{},
|
||||
}
|
||||
|
||||
if err := notFoundHandler(&ctx); err != nil {
|
||||
if err := t.errorHandler(&ctx, err); err != nil {
|
||||
log.Printf("[Error] %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (t *Tower) Use(globalMiddlewares ...Middleware) {
|
||||
t.globalMiddlewares = append(t.globalMiddlewares, globalMiddlewares...)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user