-
Notifications
You must be signed in to change notification settings - Fork 91
/
main.go
68 lines (53 loc) · 1.56 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"github.com/kataras/iris/v12"
"github.com/iris-contrib/middleware/throttler"
"github.com/throttled/throttled/v2"
"github.com/throttled/throttled/v2/store/memstore"
)
func main() {
app := iris.New()
app.Logger().SetLevel("debug")
app.Get("/", indexHandler)
middleware := newRateLimiterMiddleware(20)
limited := app.Party("/limited", middleware)
{
limited.Get("/", limitedHandler)
}
// GET: http://localhost:8080
// GET: http://localhost:8080/limited
app.Listen(":8080")
}
// The following example demonstrates the usage of `throttler.RateLimiter` for rate-limiting access
// to 20 requests per path per minute with bursts of up to 5 additional requests.
//
// For more details and customization please read the documentation of:
// https://github.com/throttled/throttled
//
// The iris-contrib/throttler middleare is the equivalent of:
// https://github.com/throttled/throttled/blob/master/http.go.
func newRateLimiterMiddleware(maxRatePerMinute int) iris.Handler {
store, err := memstore.New(65536)
if err != nil {
panic(err)
}
quota := throttled.RateQuota{
MaxRate: throttled.PerMin(maxRatePerMinute),
MaxBurst: 5,
}
rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
if err != nil {
panic(err)
}
httpRateLimiter := throttler.RateLimiter{
RateLimiter: rateLimiter,
VaryBy: &throttled.VaryBy{Path: true},
}
return httpRateLimiter.RateLimit
}
func indexHandler(ctx iris.Context) {
ctx.HTML("<h1> Index Page (no limits) </h1>")
}
func limitedHandler(ctx iris.Context) {
ctx.JSON(iris.Map{"msg": "hello"})
}