add sub router for http

pull/1208/head
longXboy 3 years ago
parent 5d07a94b16
commit 078ca6bc9b
  1. 2
      examples/http/middlewares/handlers.go
  2. 4
      examples/http/middlewares/main.go
  3. 8
      transport/http/router.go
  4. 10
      transport/http/server.go

@ -9,7 +9,7 @@ import (
func sayHelloHandler(ctx http.Context) error { func sayHelloHandler(ctx http.Context) error {
var in helloworld.HelloRequest var in helloworld.HelloRequest
if err := ctx.Bind(&in); err != nil { if err := ctx.BindQuery(&in); err != nil {
return err return err
} }

@ -30,6 +30,10 @@ func main() {
// add path filter to custom route // add path filter to custom route
r.GET("/hello/{name}", sayHelloHandler, pathFilter, pathFilter2) 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( app := kratos.New(
kratos.Name("helloworld"), kratos.Name("helloworld"),
kratos.Server( kratos.Server(

@ -29,6 +29,14 @@ func newRouter(prefix string, srv *Server, filters ...FilterFunc) *Router {
return r 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. // 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) { func (r *Router) Handle(method, relativePath string, h HandlerFunc, filters ...FilterFunc) {
next := http.Handler(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { next := http.Handler(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {

@ -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. // Server is an HTTP server wrapper.
type Server struct { type Server struct {
*http.Server *http.Server
@ -185,6 +192,9 @@ func (s *Server) filter() mux.MiddlewareFunc {
// http://127.0.0.1:8000?isSecure=false // http://127.0.0.1:8000?isSecure=false
func (s *Server) Endpoint() (*url.URL, error) { func (s *Server) Endpoint() (*url.URL, error) {
s.once.Do(func() { s.once.Do(func() {
if s.endpoint != nil {
return
}
lis, err := net.Listen(s.network, s.address) lis, err := net.Listen(s.network, s.address)
if err != nil { if err != nil {
s.err = err s.err = err

Loading…
Cancel
Save