github.com/ulule/limiter/v3@v3.11.3-0.20230613131926-4cb9c1da4633/limiter.go (about) 1 package limiter 2 3 import ( 4 "context" 5 ) 6 7 // ----------------------------------------------------------------- 8 // Context 9 // ----------------------------------------------------------------- 10 11 // Context is the limit context. 12 type Context struct { 13 Limit int64 14 Remaining int64 15 Reset int64 16 Reached bool 17 } 18 19 // ----------------------------------------------------------------- 20 // Limiter 21 // ----------------------------------------------------------------- 22 23 // Limiter is the limiter instance. 24 type Limiter struct { 25 Store Store 26 Rate Rate 27 Options Options 28 } 29 30 // New returns an instance of Limiter. 31 func New(store Store, rate Rate, options ...Option) *Limiter { 32 opt := Options{ 33 IPv4Mask: DefaultIPv4Mask, 34 IPv6Mask: DefaultIPv6Mask, 35 TrustForwardHeader: false, 36 } 37 for _, o := range options { 38 o(&opt) 39 } 40 return &Limiter{ 41 Store: store, 42 Rate: rate, 43 Options: opt, 44 } 45 } 46 47 // Get returns the limit for given identifier. 48 func (limiter *Limiter) Get(ctx context.Context, key string) (Context, error) { 49 return limiter.Store.Get(ctx, key, limiter.Rate) 50 } 51 52 // Peek returns the limit for given identifier, without modification on current values. 53 func (limiter *Limiter) Peek(ctx context.Context, key string) (Context, error) { 54 return limiter.Store.Peek(ctx, key, limiter.Rate) 55 } 56 57 // Reset sets the limit for given identifier to zero. 58 func (limiter *Limiter) Reset(ctx context.Context, key string) (Context, error) { 59 return limiter.Store.Reset(ctx, key, limiter.Rate) 60 } 61 62 // Increment increments the limit by given count & gives back the new limit for given identifier 63 func (limiter *Limiter) Increment(ctx context.Context, key string, count int64) (Context, error) { 64 return limiter.Store.Increment(ctx, key, count, limiter.Rate) 65 }