MCPcopy Create free account
hub / github.com/devaccuracy/ledgerforge / RateLimitMiddleware

Function RateLimitMiddleware

api/middleware/middleware.go:39–67  ·  view source on GitHub ↗

RateLimitMiddleware creates a middleware for rate limiting using Tollbooth. It sets up rate limiting based on the configuration parameters and applies it to incoming requests. Parameters: - conf: The configuration object containing rate limit settings. Returns: - gin.HandlerFunc: A middleware func

(conf *config.Configuration)

Source from the content-addressed store, hash-verified

37// Returns:
38// - gin.HandlerFunc: A middleware function that applies rate limiting to requests.
39func RateLimitMiddleware(conf *config.Configuration) gin.HandlerFunc {
40 if conf.RateLimit.RequestsPerSecond == nil || conf.RateLimit.Burst == nil {
41 // Rate limiting is disabled if RequestsPerSecond or Burst are not set.
42 return func(c *gin.Context) {
43 c.Next()
44 }
45 }
46
47 rps := *conf.RateLimit.RequestsPerSecond
48 burst := *conf.RateLimit.Burst
49 ttl := time.Duration(*conf.RateLimit.CleanupIntervalSec) * time.Second
50
51 // Create a new Tollbooth limiter with the specified rate and expiration time.
52 lmt := tollbooth.NewLimiter(rps, &limiter.ExpirableOptions{
53 DefaultExpirationTTL: ttl,
54 })
55 lmt.SetBurst(burst)
56
57 // Middleware function that applies rate limiting to requests.
58 return func(c *gin.Context) {
59 httpError := tollbooth.LimitByRequest(lmt, c.Writer, c.Request)
60 if httpError != nil {
61 // Respond with an error if the request exceeds the rate limit.
62 c.AbortWithStatusJSON(httpError.StatusCode, gin.H{"error": httpError.Message})
63 return
64 }
65 c.Next()
66 }
67}
68
69// MetricsAuth returns a middleware that controls access to the /metrics endpoint.
70//

Callers 2

NewAPIFunction · 0.92
TestRateLimitMiddlewareFunction · 0.85

Calls

no outgoing calls

Tested by 1

TestRateLimitMiddlewareFunction · 0.68