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") }