中间件

最后更新于:2022-04-02 02:47:46

[TOC] ## 设置默认中间件 ``` r := gin.New() // 没有中间件 r := gin.Default() //有中间件 ``` ## 三种中间件 ### 全局中间件 ``` r.Use(custromMidd) ``` ### 路由中间件 ``` r.GET("/benchmark", middleware(), benchEndpoint) ``` ### group 路由中间件 ``` authorized := r.Group("/") authorized.Use(AuthRequired()) { authorized.POST("/login", benchEndpoint) } ``` ## 定义中间件的两种方式 ``` r.Use(customMiddle()) // 方式一 func customMiddle(g *gin.Context) { foo1() g.Next() } // 方式二 func customMiddle() gin.HandlerFunc { Foo() // Foo() 将只执行一次,用于对某些第三方服务器的初始化 return func(c *gin.Context) { foo1() c.Next() } } ``` demo ``` func respondWithError(code int, message string,c *gin.Context) { resp := map[string]string{"error": message} c.JSON(code, resp) c.Abort() } func TokenAuthMiddleware() gin.HandlerFunc { return func(c *gin.Context) { token := c.Request.FormValue("api_token") if token == "" { respondWithError(401, "API token required", c) return } if token != os.Getenv("API_TOKEN") { respondWithError(401, "Invalid API token", c) return } c.Next() } } ``` ## 中间件的前置后置 ``` func Logger() gin.HandlerFunc { return func(c *gin.Context) { t := time.Now() // Set example variable c.Set("example", "12345") // before request c.Next() // after request latency := time.Since(t) log.Print(latency) // access the status we are sending status := c.Writer.Status() log.Println(status) } } ```
';