【get√】golang新手理解了一点点gin框架的中间件

1.通过use()来使用多个中间件

router := gin.New()
router.Use( middleware1, middleware2)

2.中间件的典型实现

func Logger() gin.HandlerFunc {
	return func(context *gin.Context) {
		start := time.Now()
		log.Println(start, context.Request.Method, context.Request.RequestURI, context.ClientIP())
		//上面的代码是 before_request
		context.Next()  //执行请求
		//后面的代码是after request
		latency := time.Now().Sub(start)
		log.Println(latency.Milliseconds(), context.Writer.Status())
	}
}

一直在找BeforeRequest() / AfterRequest() 这样的方法,原来很简单,写在 context.Next() 前后就行了!

猜你喜欢

转载自www.cnblogs.com/ahfuzhang/p/12891404.html