Using middleware

  1. func main() {
  2. // Creates a router without any middleware by default
  3. r := gin.New()
  4. // Global middleware
  5. // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.
  6. // By default gin.DefaultWriter = os.Stdout
  7. r.Use(gin.Logger())
  8. // Recovery middleware recovers from any panics and writes a 500 if there was one.
  9. r.Use(gin.Recovery())
  10. // Per route middleware, you can add as many as you desire.
  11. r.GET("/benchmark", MyBenchLogger(), benchEndpoint)
  12. // Authorization group
  13. // authorized := r.Group("/", AuthRequired())
  14. // exactly the same as:
  15. authorized := r.Group("/")
  16. // per group middleware! in this case we use the custom created
  17. // AuthRequired() middleware just in the "authorized" group.
  18. authorized.Use(AuthRequired())
  19. {
  20. authorized.POST("/login", loginEndpoint)
  21. authorized.POST("/submit", submitEndpoint)
  22. authorized.POST("/read", readEndpoint)
  23. // nested group
  24. testing := authorized.Group("testing")
  25. testing.GET("/analytics", analyticsEndpoint)
  26. }
  27. // Listen and serve on 0.0.0.0:8080
  28. r.Run(":8080")
  29. }

Last modified March 7, 2020 : add blog dir (#115) (f46734b)