|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "log" |
| 5 | + "net/http" |
| 6 | + "strconv" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/kataras/iris/v12" |
| 10 | + |
| 11 | + "github.com/ulule/limiter/v3" |
| 12 | + "github.com/ulule/limiter/v3/drivers/store/memory" |
| 13 | +) |
| 14 | + |
| 15 | +func main() { |
| 16 | + app := iris.New() |
| 17 | + app.Get("/hello", IPRateLimit(), helloWorldHandler) // 3. Use middleware |
| 18 | + app.Run(iris.Addr(":8080")) |
| 19 | +} |
| 20 | + |
| 21 | +func helloWorldHandler(ctx iris.Context) { |
| 22 | + err := ctx.StopWithJSON(iris.StatusOK, iris.Map{ |
| 23 | + "message": "Hello World!", |
| 24 | + }) |
| 25 | + if err != nil { |
| 26 | + return |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +func IPRateLimit() iris.Handler { |
| 31 | + // 1. Configure |
| 32 | + rate := limiter.Rate{ |
| 33 | + Period: 2 * time.Second, |
| 34 | + Limit: 1, |
| 35 | + } |
| 36 | + store := memory.NewStore() |
| 37 | + ipRateLimiter := limiter.New(store, rate) |
| 38 | + |
| 39 | + // 2. Return middleware handler |
| 40 | + return func(ctx iris.Context) { |
| 41 | + ip := ctx.RemoteAddr() |
| 42 | + limiterCtx, err := ipRateLimiter.Get(ctx.Request().Context(), ip) |
| 43 | + if err != nil { |
| 44 | + log.Printf("IPRateLimit - ipRateLimiter.Get - err: %v, %s on %s", err, ip, ctx.Request().URL) |
| 45 | + ctx.StatusCode(http.StatusInternalServerError) |
| 46 | + ctx.JSON(iris.Map{ |
| 47 | + "success": false, |
| 48 | + "message": err, |
| 49 | + }) |
| 50 | + return |
| 51 | + } |
| 52 | + |
| 53 | + ctx.Header("X-RateLimit-Limit", strconv.FormatInt(limiterCtx.Limit, 10)) |
| 54 | + ctx.Header("X-RateLimit-Remaining", strconv.FormatInt(limiterCtx.Remaining, 10)) |
| 55 | + ctx.Header("X-RateLimit-Reset", strconv.FormatInt(limiterCtx.Reset, 10)) |
| 56 | + |
| 57 | + if limiterCtx.Reached { |
| 58 | + log.Printf("Too Many Requests from %s on %s", ip, ctx.Request().URL) |
| 59 | + ctx.StatusCode(http.StatusTooManyRequests) |
| 60 | + ctx.JSON(iris.Map{ |
| 61 | + "success": false, |
| 62 | + "message": "Too Many Requests on " + ctx.Request().URL.String(), |
| 63 | + }) |
| 64 | + return |
| 65 | + } |
| 66 | + ctx.Next() |
| 67 | + } |
| 68 | +} |
0 commit comments