英文:
Gin and middleware
问题
如何创建一个中间件,使其只对某些处理程序起作用(而不是全部处理程序)?
例如,
func (srv *server) Router(repository storage.Repository, cfg config.Flags) *gin.Engine {
h := handlers.NewHandlerProvider()
m := middlewares.NewMiddlewareProvider()
srv.httpServer.Use(gin.Recovery())
srv.httpServer.Use(m.LogHTTPHandler())
srv.httpServer.POST("/", FirstHandler)
srv.httpServer.GET("/qwe", SecondHandler)
return srv.httpServer
}
我只想让 m.LogHTTPHandler() 仅在 FirstHandler 中起作用,而不是两个处理程序都起作用。
英文:
How to make a middleware so that it only works for some handlers (not for all)?
For example,
func (srv *server) Router(repository storage.Repository, cfg config.Flags) *gin.Engine {
h := handlers.NewHandlerProvider()
m := middlewares.NewMiddlewareProvider()
srv.httpServer.Use(gin.Recovery())
srv.httpServer.Use(m.LogHTTPHandler())
srv.httpServer.POST("/", FirstHandler)
srv.httpServer.GET("/qwe", SecondHandler)
return srv.httpServer
}
I just want m.LogHTTPHandler() to work only with FirstHandler, not both
答案1
得分: 2
使用gin.RouterGroup
来分组具有共同中间件的所有路由:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
// New返回一个新的空白Engine实例,没有附加任何中间件。
router := gin.New()
g1 := router.Group("/")
{
// 将日志记录中间件添加到第一组。
g1.Use(gin.Logger())
g1.GET("/", gin.HandlerFunc(func(ctx *gin.Context) {
fmt.Println("FirstHandler")
}))
}
g2 := router.Group("/qwe")
{
g2.GET("/", gin.HandlerFunc(func(ctx *gin.Context) {
fmt.Println("/SecondHandler")
}))
}
router.Run(":8080")
}
英文:
Use gin.RouterGroup
to group all the routes that have common middlewares:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
// New returns a new blank Engine instance without any middleware attached.
router := gin.New()
g1 := router.Group("/")
{
// Add the logger middleware to group 1.
g1.Use(gin.Logger())
g1.GET("/", gin.HandlerFunc(func(ctx *gin.Context) {
fmt.Println("FirstHandler")
}))
}
g2 := router.Group("/qwe")
{
g2.GET("/", gin.HandlerFunc(func(ctx *gin.Context) {
fmt.Println("/SecondHandler")
}))
}
router.Run(":8080")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论