g.Meta Add middleware to a single address when using canonical routing
Is your feature request related to a problem?
Option Yes
Describe the solution you'd like
规范路由请求:
type CreateTaskReq struct {
g.Meta `path:"/create" method:"post" tags:"任务" summary:"新建任务"`
xxx
}
主函数:
func main() {
s := g.Server()
s.Use(
ghttp.MiddlewareCORS,
ghttp.MiddlewareHandlerResponse,
middleware.MiddlewareLog,
)
s.Group("/task", func(group *ghttp.RouterGroup) {
group.Bind(
task.NewV1(),
)
})
s.Run()
}
Describe alternatives you've considered
需求:
我想给 /task 这个地址下 /task/create 这个路由添加一个鉴权的中间件
希望能在 g.Meta 中有一个 middleware 中间件的数组 就很方便了
获取有其他的解决办法
Additional
No response
其实有好办法,在元数据中加个标识,通过统一的中间件读取这个标识做判断。我搞个example和文档。
Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑🤝🧑👫🧑🏿🤝🧑🏻👩🏾🤝👨🏿👬🏿
In fact, there is a good way to add an identifier to the metadata and use unified middleware to read this identifier to make judgments. I'll make an example and documentation.
其实有好办法,在元数据中加个标识,通过统一的中间件读取这个标识做判断。我搞个example和文档。
中间件只拿到个 r *ghttp.Request,要怎么获取到元数据呢?~~看了一圈好像并没有获取 XxxReq XxxRes 的办法~~
可以用 r.GetServeHandler().Handler.Info.Type 拿到路由方法的反射类型:
func MiddlewareDemo(r *ghttp.Request) {
handler := r.GetServeHandler()
var req reflect.Type = handler.Handler.Info.Type.In(1)
var res reflect.Type = handler.Handler.Info.Type.Out(0)
logger := g.Log("MiddlewareDemo")
logger.Warning(r.Context(), req) // *v1.XxxReq
logger.Warning(r.Context(), res) // *v1.XxxRes
logger.Warningf(r.Context(), "Reading meta tag `%s`: %s", "path", handler.GetMetaTag("path"))
logger.Warningf(r.Context(), "Reading meta tag `%s`: %s", "tags", handler.GetMetaTag("tags"))
logger.Warningf(r.Context(), "Reading meta tag `%s`: %s", "custom", handler.GetMetaTag("custom"))
r.Middleware.Next()
}