diff --git a/examples/http/middlewares/handlers.go b/examples/http/middlewares/handlers.go index 08950ecef..117d5056c 100644 --- a/examples/http/middlewares/handlers.go +++ b/examples/http/middlewares/handlers.go @@ -9,7 +9,7 @@ import ( func sayHelloHandler(ctx http.Context) error { var in helloworld.HelloRequest - if err := ctx.Bind(&in); err != nil { + if err := ctx.BindQuery(&in); err != nil { return err } diff --git a/examples/http/middlewares/main.go b/examples/http/middlewares/main.go index f5cb2b3d0..4d63b00d7 100644 --- a/examples/http/middlewares/main.go +++ b/examples/http/middlewares/main.go @@ -30,6 +30,10 @@ func main() { // add path filter to custom route r.GET("/hello/{name}", sayHelloHandler, pathFilter, pathFilter2) + // add path filter to sub router + r2 := r.NewSubRouter("/v2", pathFilter, pathFilter2) + r2.GET("/say/{name}", sayHelloHandler) + app := kratos.New( kratos.Name("helloworld"), kratos.Server( diff --git a/transport/http/router.go b/transport/http/router.go index 3c0550ddd..b0e36f85e 100644 --- a/transport/http/router.go +++ b/transport/http/router.go @@ -29,6 +29,14 @@ func newRouter(prefix string, srv *Server, filters ...FilterFunc) *Router { return r } +// NewSubRouter returns a new sub router +func (r *Router) NewSubRouter(prefix string, filters ...FilterFunc) *Router { + var newFilters []FilterFunc + newFilters = append(newFilters, r.filters...) + newFilters = append(newFilters, filters...) + return newRouter(path.Join(r.prefix, prefix), r.srv, newFilters...) +} + // Handle registers a new route with a matcher for the URL path and method. func (r *Router) Handle(method, relativePath string, h HandlerFunc, filters ...FilterFunc) { next := http.Handler(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { diff --git a/transport/http/server.go b/transport/http/server.go index cc314bfa1..8a4f8a20b 100644 --- a/transport/http/server.go +++ b/transport/http/server.go @@ -86,6 +86,13 @@ func ErrorEncoder(en EncodeErrorFunc) ServerOption { } } +// Endpoint with server endpoint. +func Endpoint(endpoint *url.URL) ServerOption { + return func(o *Server) { + o.endpoint = endpoint + } +} + // Server is an HTTP server wrapper. type Server struct { *http.Server @@ -185,6 +192,9 @@ func (s *Server) filter() mux.MiddlewareFunc { // http://127.0.0.1:8000?isSecure=false func (s *Server) Endpoint() (*url.URL, error) { s.once.Do(func() { + if s.endpoint != nil { + return + } lis, err := net.Listen(s.network, s.address) if err != nil { s.err = err