zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    supervisor 简单使用
    golang的表格驱动测试
    golang和python的二进制转换
    django-rest-framework-jwt的使用
    threading.local在flask中的用法
    分布式的两种算法
    第24课
    Mock以及Mockito的使用
    java下使用chromedriver获取访问页面状态码
    Mockito:一个强大的用于Java开发的模拟测试框架
  • 原文地址:https://www.cnblogs.com/qzhc/p/13454596.html
Copyright © 2011-2022 走看看