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
- go get -u github.com/gofiber/limiter
Signature
- limiter.New(config ...Config) func(*Ctx)
Config
Property | Type | Description | Default |
---|---|---|---|
Filter | func(fiber.Ctx) bool | Defines a function to skip middleware | nil |
Timeout | int | Timeout in seconds on how long to keep records of requests in memory | 60 |
Max | int | Max number of recent connections during Timeout seconds before sending a 429 response | 10 |
Message | string | Response body | “Too many requests, please try again later.” |
StatusCode | int | Response status code | 429 |
Key | func(Ctx) string | A function that allows to create custom keys. By default c.IP() is used. | nil |
Handler | func(*Ctx) | Handler is called when a request hits the limit | nil |
Example
- package main
- import (
- "github.com/gofiber/fiber"
- "github.com/gofiber/limiter"
- )
- func main() {
- app := fiber.New()
- // 3 requests per 10 seconds max
- cfg := limiter.Config{
- Timeout: 10,
- Max: 3,
- }
- app.Use(limiter.New(cfg))
- app.Get("/", func(c *fiber.Ctx) {
- c.Send("Welcome!")
- })
- app.Listen(3000)
- }