gin 怎么写个简单的中间件

我们两清 提交于 2020-08-14 05:38:34

gin 写个简单中间件,直接上例子:

func GinServer() {
	engine := gin.Default()
	engine.Use(TestMiddleware)
	engine.GET("/", func(context *gin.Context) {
		context.JSON(http.StatusOK, "test")
	})
	engine.Run(":8080")
}

func TestMiddleware(context *gin.Context) {
	fmt.Println("这是一个简单的中间件")
}

这个例子最主要的方法是Use,看下Use方法

// Use attaches a global middleware to the router. ie. the middleware attached though Use() will be
// included in the handlers chain for every single request. Even 404, 405, static files...
// For example, this is the right place for a logger or error management middleware.
func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {
	engine.RouterGroup.Use(middleware...)
	engine.rebuild404Handlers()
	engine.rebuild405Handlers()
	return engine
}

在Use中添加中间件是作用于路由上,并且Use接受参数是一个HandlerFunc 切片,可以添加多个中间件,组成一个 chain,所以在添加中间件的时候也要主要顺序。不同的路由组也可以添加不同的中间件,这点上gin很灵活的处理了路由。如下代码,在不同的路由组中定义不用中间件:

    v1 := engine.Group("v1/")

	v1.Use(TestMiddleware1)
	{
		v1.GET("ping", func(context *gin.Context) {
			context.String(http.StatusOK,"成功")
		})

	}
	v2 := engine.Group("v2/")
	v2.Use(TestMiddleware3)
	{
		v2.GET("ping", func(context *gin.Context) {
			context.String(http.StatusOK,"成功1")
		})

	}

gin的路由组概念在写api 的时候非常的灵活。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!