Skip to content

Commit 19fc17d

Browse files
Add docs from gofiber/fiber@011c8f8
1 parent 9b6946f commit 19fc17d

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

docs/core/middleware/limiter.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ app.Use(limiter.New(limiter.Config{
4343
return c.IP() == "127.0.0.1"
4444
},
4545
Max: 20,
46+
MaxFunc: func(c fiber.Ctx) int {
47+
return 20
48+
},
4649
Expiration: 30 * time.Second,
4750
KeyGenerator: func(c fiber.Ctx) string {
4851
return c.Get("x-forwarded-for")
@@ -75,12 +78,28 @@ weightOfPreviousWindow = previous window's amount request * (whenNewWindow / Exp
7578
rate = weightOfPreviousWindow + current window's amount request.
7679
```
7780

81+
## Dynamic limit
82+
83+
You can also calculate the limit dynamically using the MaxFunc parameter. It's a function that receives the request's context as a parameter and allow you to calculate a different limit for each request separately.
84+
85+
Example:
86+
87+
```go
88+
app.Use(limiter.New(limiter.Config{
89+
MaxFunc: func(c fiber.Ctx) int {
90+
return getUserLimit(ctx.Param("id"))
91+
},
92+
Expiration: 30 * time.Second,
93+
}))
94+
```
95+
7896
## Config
7997

8098
| Property | Type | Description | Default |
8199
|:-----------------------|:--------------------------|:--------------------------------------------------------------------------------------------|:-----------------------------------------|
82100
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
83101
| Max | `int` | Max number of recent connections during `Expiration` seconds before sending a 429 response. | 5 |
102+
| MaxFunc | `func(fiber.Ctx) int` | A function to calculate the max number of recent connections during `Expiration` seconds before sending a 429 response. | A function which returns the cfg.Max |
84103
| KeyGenerator | `func(fiber.Ctx) string` | KeyGenerator allows you to generate custom keys, by default c.IP() is used. | A function using c.IP() as the default |
85104
| Expiration | `time.Duration` | Expiration is the time on how long to keep records of requests in memory. | 1 * time.Minute |
86105
| LimitReached | `fiber.Handler` | LimitReached is called when a request hits the limit. | A function sending 429 response |
@@ -101,6 +120,9 @@ A custom store can be used if it implements the `Storage` interface - more detai
101120
```go
102121
var ConfigDefault = Config{
103122
Max: 5,
123+
MaxFunc: func(c fiber.Ctx) int {
124+
return 5
125+
},
104126
Expiration: 1 * time.Minute,
105127
KeyGenerator: func(c fiber.Ctx) string {
106128
return c.IP()

0 commit comments

Comments
 (0)