Limiter

Use to limit repeated requests to public APIs and/or endpoints such as password reset. This middleware does not share state with other processes/servers.

Installation

  1. go get -u github.com/gofiber/limiter

Signature

  1. limiter.New(config ...Config) func(*Ctx)

Config

PropertyTypeDescriptionDefault
Filterfunc(fiber.Ctx) boolDefines a function to skip middlewarenil
TimeoutintTimeout in seconds on how long to keep records of requests in memory60
MaxintMax number of recent connections during Timeout seconds before sending a 429 response10
MessagestringResponse body“Too many requests, please try again later.”
StatusCodeintResponse status code429
Keyfunc(Ctx) stringA function that allows to create custom keys. By default c.IP() is used.nil
Handlerfunc(*Ctx)Handler is called when a request hits the limitnil

Example

  1. package main
  2.  
  3. import (
  4. "github.com/gofiber/fiber"
  5. "github.com/gofiber/limiter"
  6. )
  7.  
  8. func main() {
  9. app := fiber.New()
  10.  
  11. // 3 requests per 10 seconds max
  12. cfg := limiter.Config{
  13. Timeout: 10,
  14. Max: 3,
  15. }
  16.  
  17. app.Use(limiter.New(cfg))
  18.  
  19. app.Get("/", func(c *fiber.Ctx) {
  20. c.Send("Welcome!")
  21. })
  22.  
  23. app.Listen(3000)
  24. }