1.7 gin中间件

  • 分类使用方式
    “`
    // 1.全局中间件
    router.Use(gin.Logger())
    router.Use(gin.Recovery())

// 2.单路由的中间件,可以加任意多个
router.GET(“/benchmark”, MyMiddelware(), benchEndpoint)

// 3.群组路由的中间件
authorized := router.Group(“/“, MyMiddelware())
// 或者这样用:
authorized := router.Group(“/“)
authorized.Use(MyMiddelware())
{
authorized.POST(“/login”, loginEndpoint)
}

<a name="middleware-create"></a>- 自定义中间件```go//定义func Logger() gin.HandlerFunc {    return func(c *gin.Context) {        t := time.Now()        // 在gin上下文中定义变量        c.Set("example", "12345")        // 请求前        c.Next()//处理请求        // 请求后        latency := time.Since(t)        log.Print(latency)        // access the status we are sending        status := c.Writer.Status()        log.Println(status)    }}//使用func main() {    r := gin.New()    r.Use(Logger())    r.GET("/test", func(c *gin.Context) {        //获取gin上下文中的变量        example := c.MustGet("example").(string)        // 会打印: "12345"        log.Println(example)    })    // 监听运行于 0.0.0.0:8080    r.Run(":8080")}
  • 中间件参数
  • 内置中间件
    1.简单认证BasicAuth
// 模拟私有数据var secrets = gin.H{    "foo":    gin.H{"email": "foo@bar.com", "phone": "123433"},    "austin": gin.H{"email": "austin@example.com", "phone": "666"},    "lena":   gin.H{"email": "lena@guapa.com", "phone": "523443"},}func main() {    r := gin.Default()    // 使用 gin.BasicAuth 中间件,设置授权用户    authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{        "foo":    "bar",        "austin": "1234",        "lena":   "hello2",        "manu":   "4321",    }))    // 定义路由    authorized.GET("/secrets", func(c *gin.Context) {        // 获取提交的用户名(AuthUserKey)        user := c.MustGet(gin.AuthUserKey).(string)        if secret, ok := secrets[user]; ok {            c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})        } else {            c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})        }    })    // Listen and serve on 0.0.0.0:8080    r.Run(":8080")}

Leave a Reply

Your email address will not be published. Required fields are marked *