gin实现中间件middleware

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

正在整理笔记, 如有雷同,请告知,必添加!

原文地址:https://www.cnblogs.com/qzhc/p/13454596.html