From 2f9d7f892cf1af1771daaff3e0cc2f5c7e54c571 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Sun, 22 May 2022 23:24:48 +0800 Subject: [PATCH] http/bm: add prefix matcher for the path prefix (#2020) * add prefix matcher for the path prefix * fix prefix path --- pkg/net/http/blademaster/routergroup.go | 24 ++++++++++++++++++++++++ pkg/net/http/blademaster/server.go | 16 ++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/pkg/net/http/blademaster/routergroup.go b/pkg/net/http/blademaster/routergroup.go index 281796b12..71c0e7b74 100644 --- a/pkg/net/http/blademaster/routergroup.go +++ b/pkg/net/http/blademaster/routergroup.go @@ -2,6 +2,7 @@ package blademaster import ( "regexp" + "strings" ) // IRouter http router framework interface. @@ -49,6 +50,29 @@ func (group *RouterGroup) UseFunc(middleware ...HandlerFunc) IRoutes { 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. // For example, all the routes that use a common middlware for authorization could be grouped. func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { diff --git a/pkg/net/http/blademaster/server.go b/pkg/net/http/blademaster/server.go index 63187306a..871679e01 100644 --- a/pkg/net/http/blademaster/server.go +++ b/pkg/net/http/blademaster/server.go @@ -392,6 +392,22 @@ func (engine *Engine) Use(middleware ...Handler) IRoutes { 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. func (engine *Engine) Ping(handler HandlerFunc) { engine.GET("/ping", handler)