Limiter

Limiter middleware for Fiber used to limit repeated requests to public APIs and/or endpoints such as password reset etc. Also useful for API clients, web crawling, or other tasks that need to be throttled.

Signatures

  1. func New(config ...Config) fiber.Handler

Examples

Import the middleware package that is part of the Fiber web framework

  1. import (
  2. "github.com/gofiber/fiber/v2"
  3. "github.com/gofiber/fiber/v2/middleware/limiter"
  4. )

After you initiate your Fiber app, you can use the following possibilities:

  1. // Default middleware config
  2. app.Use(limiter.New())
  3. // Or extend your config for customization
  4. app.Use(limiter.New(limiter.Config{
  5. Next: func(c *fiber.Ctx) bool {
  6. return c.IP() == "127.0.0.1"
  7. },
  8. Max: 20,
  9. Duration: 30 * time.Second,
  10. Key: func(c *fiber.Ctx) string {
  11. return c.Get("x-forwarded-for")
  12. },
  13. LimitReached: func(c *fiber.Ctx) error {
  14. return c.SendFile("./toofast.html")
  15. },
  16. }))

Config

  1. // Config defines the config for middleware.
  2. type Config struct {
  3. // Next defines a function to skip this middleware when returned true.
  4. //
  5. // Optional. Default: nil
  6. Next func(c *fiber.Ctx) bool
  7. // Max number of recent connections during `Duration` seconds before sending a 429 response
  8. //
  9. // Default: 5
  10. Max int
  11. // Duration is the time on how long to keep records of requests in memory
  12. //
  13. // Default: time.Minute
  14. Duration time.Duration
  15. // Key allows you to generate custom keys, by default c.IP() is used
  16. //
  17. // Default: func(c *fiber.Ctx) string {
  18. // return c.IP()
  19. // }
  20. Key func(*fiber.Ctx) string
  21. // LimitReached is called when a request hits the limit
  22. //
  23. // Default: func(c *fiber.Ctx) error {
  24. // return c.SendStatus(fiber.StatusTooManyRequests)
  25. // }
  26. LimitReached fiber.Handler
  27. }

Default Config

  1. var ConfigDefault = Config{
  2. Next: nil,
  3. Max: 5,
  4. Duration: time.Minute,
  5. Key: func(c *fiber.Ctx) string {
  6. return c.IP()
  7. },
  8. LimitReached: func(c *fiber.Ctx) error {
  9. return c.SendStatus(fiber.StatusTooManyRequests)
  10. },
  11. }