github.com/ulule/limiter/v3@v3.11.3-0.20230613131926-4cb9c1da4633/drivers/middleware/gin/options.go (about) 1 package gin 2 3 import ( 4 "net/http" 5 6 "github.com/gin-gonic/gin" 7 ) 8 9 // Option is used to define Middleware configuration. 10 type Option interface { 11 apply(*Middleware) 12 } 13 14 type option func(*Middleware) 15 16 func (o option) apply(middleware *Middleware) { 17 o(middleware) 18 } 19 20 // ErrorHandler is an handler used to inform when an error has occurred. 21 type ErrorHandler func(c *gin.Context, err error) 22 23 // WithErrorHandler will configure the Middleware to use the given ErrorHandler. 24 func WithErrorHandler(handler ErrorHandler) Option { 25 return option(func(middleware *Middleware) { 26 middleware.OnError = handler 27 }) 28 } 29 30 // DefaultErrorHandler is the default ErrorHandler used by a new Middleware. 31 func DefaultErrorHandler(c *gin.Context, err error) { 32 panic(err) 33 } 34 35 // LimitReachedHandler is an handler used to inform when the limit has exceeded. 36 type LimitReachedHandler func(c *gin.Context) 37 38 // WithLimitReachedHandler will configure the Middleware to use the given LimitReachedHandler. 39 func WithLimitReachedHandler(handler LimitReachedHandler) Option { 40 return option(func(middleware *Middleware) { 41 middleware.OnLimitReached = handler 42 }) 43 } 44 45 // DefaultLimitReachedHandler is the default LimitReachedHandler used by a new Middleware. 46 func DefaultLimitReachedHandler(c *gin.Context) { 47 c.String(http.StatusTooManyRequests, "Limit exceeded") 48 } 49 50 // KeyGetter will define the rate limiter key given the gin Context. 51 type KeyGetter func(c *gin.Context) string 52 53 // WithKeyGetter will configure the Middleware to use the given KeyGetter. 54 func WithKeyGetter(handler KeyGetter) Option { 55 return option(func(middleware *Middleware) { 56 middleware.KeyGetter = handler 57 }) 58 } 59 60 // DefaultKeyGetter is the default KeyGetter used by a new Middleware. 61 // It returns the Client IP address. 62 func DefaultKeyGetter(c *gin.Context) string { 63 return c.ClientIP() 64 } 65 66 // WithExcludedKey will configure the Middleware to ignore key(s) using the given function. 67 func WithExcludedKey(handler func(string) bool) Option { 68 return option(func(middleware *Middleware) { 69 middleware.ExcludedKey = handler 70 }) 71 }