Custom Middleware

  1. func Logger() iris.Handler {
  2. return func(ctx iris.Context) {
  3. t := time.Now()
  4. // Set a shared variable between handlers
  5. ctx.Values().Set("framework", "iris")
  6. // before request
  7. ctx.Next()
  8. // after request
  9. latency := time.Since(t)
  10. log.Print(latency)
  11. // access the status we are sending
  12. status := ctx.GetStatusCode()
  13. log.Println(status)
  14. }
  15. }
  16. func main() {
  17. app := iris.New()
  18. app.Use(Logger())
  19. app.Get("/test", func(ctx iris.Context) {
  20. // retrieve a value set by the middleware.
  21. framework := ctx.Values().GetString("framework")
  22. // it would print: "iris"
  23. log.Println(framework)
  24. })
  25. app.Listen(":8080")
  26. }