1. 无中间件启动

  1. #使用
  2. r := gin.New()
  3. #替代
  4. // 默认启动方式,包含 Logger、Recovery 中间件
  5. r := gin.Default()

2. 使用中间件

  1. func main() {
  2. // 创建一个不包含中间件的路由器
  3. r := gin.New()
  4. // 全局中间件
  5. // 使用 Logger 中间件
  6. r.Use(gin.Logger())
  7. // 使用 Recovery 中间件
  8. r.Use(gin.Recovery())
  9. // 路由添加中间件,可以添加任意多个
  10. r.GET("/benchmark", MyBenchLogger(), benchEndpoint)
  11. // 路由组中添加中间件
  12. // authorized := r.Group("/", AuthRequired())
  13. // exactly the same as:
  14. authorized := r.Group("/")
  15. // per group middleware! in this case we use the custom created
  16. // AuthRequired() middleware just in the "authorized" group.
  17. authorized.Use(AuthRequired())
  18. {
  19. authorized.POST("/login", loginEndpoint)
  20. authorized.POST("/submit", submitEndpoint)
  21. authorized.POST("/read", readEndpoint)
  22. // nested group
  23. testing := authorized.Group("testing")
  24. testing.GET("/analytics", analyticsEndpoint)
  25. }
  26. // Listen and serve on 0.0.0.0:8080
  27. r.Run(":8080")
  28. }

3. 自定义组件

  1. func Logger() gin.HandlerFunc {
  2. return func(c *gin.Context) {
  3. t := time.Now()
  4. // Set example variable
  5. c.Set("example", "12345")
  6. // before request
  7. c.Next()
  8. // after request
  9. latency := time.Since(t)
  10. log.Print(latency)
  11. // access the status we are sending
  12. status := c.Writer.Status()
  13. log.Println(status)
  14. }
  15. }
  16. func main() {
  17. r := gin.New()
  18. r.Use(Logger())
  19. r.GET("/test", func(c *gin.Context) {
  20. example := c.MustGet("example").(string)
  21. // it would print: "12345"
  22. log.Println(example)
  23. })
  24. // Listen and serve on 0.0.0.0:8080
  25. r.Run(":8080")
  26. }