Gin和中间件

huangapple go评论70阅读模式
英文:

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")
}

huangapple
  • 本文由 发表于 2023年5月30日 02:41:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76359675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定