zoukankan      html  css  js  c++  java
  • gin框架使用【7.中间件使用】

    在 gin中,通过默认的函数,构建一个实现了带默认中间件的 *Engine。

    r := gin.Default()

    默认绑定了Logger和Recovery中间件,帮助我们进行日志输出和错误处理。

    func Default() *Engine {
       debugPrintWARNINGDefault()
       engine := New()
       engine.Use(Logger(), Recovery())
       return engine
    }

    func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {
    engine.RouterGroup.Use(middleware...)
    engine.rebuild404Handlers()
    engine.rebuild405Handlers()
    return engine
    }

    func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes {
    return group.handle(http.MethodPost, relativePath, handlers)
    }

    func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {
    return group.handle(http.MethodGet, relativePath, handlers)
    }

    可以看到,gin的中间件是通过 User()方法进行设置,他接收一个 HandlerFunc类型的可变参数;HandlerFunc在Gin中是很常见的一个类型。

    中间件实现BasicAuth

    在gin中,默认提供了 gin.BasicAuth 中间件,来实现基本的认证功能

    //针对全局路由的BasicAuth
    func main() { router := gin.Default() router.Use(gin.BasicAuth(gin.Accounts{ "dba" : "dbapass", })) router.GET("/users", func(c *gin.Context) { c.JSON(200, true) }) router.Run(":8080") }

    //针对路由组的BasicAuth

    func main() {
       router := gin.Default()
    v1RouterGroup := router.Group("/v1")
    v1RouterGroup.Use(gin.BasicAuth(gin.Accounts{
    "dba" : "dbapass",
    }))
    {
    v1RouterGroup.GET("/users", func(c *gin.Context) {
    c.JSON(200, true) //true
    })
    }
    router.Run(":8080")
    }

    // 针对特定路由的BasicAuth
    func main() {
    router := gin.Default()
    v1RouterGroup := router.Group("/v1")
    {
    v1RouterGroup.GET("/users", gin.BasicAuth(gin.Accounts{
    "dba" : "dbapass",
    }), func(c *gin.Context) {
    c.JSON(200, true) //true
    })
    }
    router.Run(":8080")
    }
     

      

    自定义中间件

    gin的中间件就是一个 HandlerFunc,那么只要自己实现一个 HandlerFunc 就能实现一个中间件

    func costTime() gin.HandlerFunc {
    	return func(c *gin.Context) {
    		start := time.Now()
    		c.Next()
    		costTime := time.Since(start)
    		url := c.Request.URL.String()
    		logger.Debug("url %s exec cost %d", url, costTime)
    	}
    }
    

    gin中的 Next() 和 Abrot()

    // Next should be used only inside middleware.
    // It executes the pending handlers in the chain inside the calling handler.
    // See example in GitHub.
    // 在执行的 handler 中执行HandlerFunc链中挂起的 handler func (c *Context) Next() { c.index++ for c.index < int8(len(c.handlers)) { c.handlers[c.index](c) c.index++ } }

    // Abort prevents pending handlers from being called. Note that this will not stop the current handler.
    // Let's say you have an authorization middleware that validates that the current request is authorized.
    // If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers
    // for this request are not called.
    // Abort 在被调用的函数中阻止挂起函数。注意这将不会停止当前的函数。例如,你有一个验证当前的请求是否是认证过的 Authorization 中间件。
    // 如果验证失败(例如,密码不匹配),调用 Abort 以确保这个请求的其他函数不会被调用。
    func (c *Context) Abort() {
    c.index = abortIndex
    }
  • 相关阅读:
    火狐显示不安全链接
    signal信号
    I/O缓冲
    [pe530]GCD of Divisors
    学校寒假集训作业
    纳克萨玛斯「GDOI2007」(网络流)
    [清华集训2016] 汽水
    有上下界网络流
    [AHOI2014]支线剧情(有上下界的网络流)
    [SCOI2016]妖怪
  • 原文地址:https://www.cnblogs.com/juanmaofeifei/p/14278313.html
Copyright © 2011-2022 走看看