feat: support file server in rest (#4244)

This commit is contained in:
Kevin Wan
2024-07-13 19:58:35 +08:00
committed by GitHub
parent e776b5d8ab
commit ec86f22cd6
8 changed files with 216 additions and 0 deletions

View File

@@ -13,6 +13,7 @@ import (
"github.com/zeromicro/go-zero/rest/httpx"
"github.com/zeromicro/go-zero/rest/internal"
"github.com/zeromicro/go-zero/rest/internal/cors"
"github.com/zeromicro/go-zero/rest/internal/fileserver"
"github.com/zeromicro/go-zero/rest/router"
)
@@ -170,6 +171,13 @@ func WithCustomCors(middlewareFn func(header http.Header), notAllowedFn func(htt
}
}
// WithFileServer returns a RunOption to serve files from given dir with given path.
func WithFileServer(path, dir string) RunOption {
return func(server *Server) {
server.router = newFileServingRouter(server.router, path, dir)
}
}
// WithJwt returns a func to enable jwt authentication in given route.
func WithJwt(secret string) RouteOption {
return func(r *featuredRoutes) {
@@ -337,3 +345,19 @@ func newCorsRouter(router httpx.Router, headerFn func(http.Header), origins ...s
func (c *corsRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c.middleware(c.Router.ServeHTTP)(w, r)
}
type fileServingRouter struct {
httpx.Router
middleware Middleware
}
func newFileServingRouter(router httpx.Router, path, dir string) httpx.Router {
return &fileServingRouter{
Router: router,
middleware: fileserver.Middleware(path, dir),
}
}
func (f *fileServingRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.middleware(f.Router.ServeHTTP)(w, r)
}