golang框架gin中间件的写法

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
)

func middleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        fmt.Println("I am before next")
        c.Header("Access-Control-Allow-Origin", "test")
        c.Set("name", "test")
        /*
            c.Next()后就执行真实的路由函数,路由函数执行完成之后继续执行后续的代码
        */
        c.Next()
        fmt.Println("I am after next")
    }
}

func main() {
    r := gin.Default()
    r.Use(middleware())
    r.GET("/test", func(c *gin.Context) {
        fmt.Println("I am https://www.zhouchun.net")
        name, _ := c.Get("name")
        c.JSON(200, gin.H{"name": name})
    })
    r.Run("0.0.0.0:10020")
}
    原文作者:xxfaxy
    原文地址: https://segmentfault.com/a/1190000017301776
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞