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.

Note: this module does not share state with other processes/servers by default.

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. Expiration: 30 * time.Second,
  10. KeyGenerator: 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. Store: myCustomStore{}
  17. }))

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. // KeyGenerator allows you to generate custom keys, by default c.IP() is used
  12. //
  13. // Default: func(c *fiber.Ctx) string {
  14. // return c.IP()
  15. // }
  16. KeyGenerator func(*fiber.Ctx) string
  17. // Expiration is the time on how long to keep records of requests in memory
  18. //
  19. // Default: 1 * time.Minute
  20. Expiration time.Duration
  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. // Store is used to store the state of the middleware
  28. //
  29. // Default: an in memory store for this process only
  30. Storage fiber.Storage
  31. }

A custom store can be used if it implements the Storage interface - more details and an example can be found in store.go.

Default Config

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