http/bm: add prefix matcher for the path prefix (#2020)

* add prefix matcher for the path prefix

* fix prefix path
v1.0.x
Tony Chen 3 years ago committed by GitHub
parent a9b8af4c55
commit 2f9d7f892c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 24
      pkg/net/http/blademaster/routergroup.go
  2. 16
      pkg/net/http/blademaster/server.go

@ -2,6 +2,7 @@ package blademaster
import ( import (
"regexp" "regexp"
"strings"
) )
// IRouter http router framework interface. // IRouter http router framework interface.
@ -49,6 +50,29 @@ func (group *RouterGroup) UseFunc(middleware ...HandlerFunc) IRoutes {
return group.returnObj() return group.returnObj()
} }
// Prefix adds a matcher for the URL path prefix.
func (group *RouterGroup) Prefix(prefix string, handlers ...Handler) IRoutes {
return group.PrefixFunc(prefix, func(c *Context) {
for _, h := range handlers {
h.ServeHTTP(c)
}
})
}
// PrefixFunc adds a matcher for the URL path prefix.
func (group *RouterGroup) PrefixFunc(prefix string, handlers ...HandlerFunc) IRoutes {
return group.UseFunc(func(c *Context) {
if strings.HasPrefix(c.Request.URL.Path, prefix) {
for _, h := range handlers {
h.ServeHTTP(c)
}
c.Abort()
return
}
c.Next()
})
}
// Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix. // Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
// For example, all the routes that use a common middlware for authorization could be grouped. // For example, all the routes that use a common middlware for authorization could be grouped.
func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {

@ -392,6 +392,22 @@ func (engine *Engine) Use(middleware ...Handler) IRoutes {
return engine return engine
} }
// PrefixFunc adds a matcher for the URL path prefix.
func (engine *Engine) PrefixFunc(prefix string, handlers ...HandlerFunc) IRoutes {
engine.RouterGroup.PrefixFunc(prefix, handlers...)
engine.rebuild404Handlers()
engine.rebuild405Handlers()
return engine
}
// Prefix adds a matcher for the URL path prefix.
func (engine *Engine) Prefix(prefix string, handlers ...Handler) IRoutes {
engine.RouterGroup.Prefix(prefix, handlers...)
engine.rebuild404Handlers()
engine.rebuild405Handlers()
return engine
}
// Ping is used to set the general HTTP ping handler. // Ping is used to set the general HTTP ping handler.
func (engine *Engine) Ping(handler HandlerFunc) { func (engine *Engine) Ping(handler HandlerFunc) {
engine.GET("/ping", handler) engine.GET("/ping", handler)

Loading…
Cancel
Save