mirror of
https://github.com/zeromicro/go-zero.git
synced 2026-05-07 15:10:01 +08:00
feat: support file server in rest (#4244)
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user