github.com/goravel/framework@v1.13.9/http/limit/limit.go (about) 1 package limit 2 3 import ( 4 "github.com/goravel/framework/contracts/http" 5 ) 6 7 func PerMinute(maxAttempts int) http.Limit { 8 return NewLimit(maxAttempts, 1) 9 } 10 11 func PerMinutes(decayMinutes, maxAttempts int) http.Limit { 12 return NewLimit(maxAttempts, decayMinutes) 13 } 14 15 func PerHour(maxAttempts int) http.Limit { 16 return NewLimit(maxAttempts, 60) 17 } 18 19 func PerHours(decayHours, maxAttempts int) http.Limit { 20 return NewLimit(maxAttempts, 60*decayHours) 21 } 22 23 func PerDay(maxAttempts int) http.Limit { 24 return NewLimit(maxAttempts, 60*24) 25 } 26 27 func PerDays(decayDays, maxAttempts int) http.Limit { 28 return NewLimit(maxAttempts, 60*24*decayDays) 29 } 30 31 type Limit struct { 32 // The rate limit signature key. 33 Key string 34 // The maximum number of attempts allowed within the given number of minutes. 35 MaxAttempts int 36 // The number of minutes until the rate limit is reset. 37 DecayMinutes int 38 // The response generator callback. 39 ResponseCallback func(ctx http.Context) 40 } 41 42 func NewLimit(maxAttempts, decayMinutes int) *Limit { 43 return &Limit{ 44 MaxAttempts: maxAttempts, 45 DecayMinutes: decayMinutes, 46 ResponseCallback: func(ctx http.Context) { 47 ctx.Request().AbortWithStatus(http.StatusTooManyRequests) 48 }, 49 } 50 } 51 52 func (r *Limit) By(key string) http.Limit { 53 r.Key = key 54 55 return r 56 } 57 58 func (r *Limit) Response(callable func(ctx http.Context)) http.Limit { 59 r.ResponseCallback = callable 60 61 return r 62 }