func main() { engine := gin.Default() engine.Use(RequestInfos()) engine.GET("/query", func(context *gin.Context) { context.JSON(200,map[string] interface{}{ "code": 1, "msg": context.FullPath(), }) }) engine.Run(":8888") } //打印請求的中間件;在調用http://localhost:8080/query之前調用下面方法 func RequestInfos() gin.HandlerFunc { return func(context *gin.Context) { path := context.FullPath() method := context.Request.Method fmt.Println("path-->"+path) fmt.Println("method--->"+method) } }
如果有多個請求,如果想讓單獨的某個請求來使用RequestInfos
//直接放到第二個參數上 engine := gin.Default() //engine.Use(RequestInfos()) engine.GET("/query", RequestInfos(),func(context *gin.Context) {
當query處理完后,處理結束后的信息也通過中間件打印出來. context.Next()
1、engine.Use(RequestInfos()) 3、engine.GET("/query", func(context *gin.Context) { context.JSON(404,map[string] interface{}{ "code": 1, "msg": context.FullPath(), }) }) engine.Run(":8888") } //打印請求的中間件;在調用query之前調用 func RequestInfos() gin.HandlerFunc { return func(context *gin.Context) { --------2、fmt.Println("狀態碼:",context.Writer.Status()) path := context.FullPath() method := context.Request.Method fmt.Println("path-->"+path) fmt.Println("method--->"+method) //***************** context.Next() --------4、fmt.Println("狀態碼:",context.Writer.Status()) 執行順序:如上 打印結果: 狀態碼: 200 path-->/query method--->GET 狀態碼: 404
正在整理筆記, 如有雷同,請告知,必添加!