Rate Limiting
Limit the user lookup from Your First Route to one request per minute for each client IP that connects directly to the app.
Limit the User Route
Add these imports to internal/users/controller.go.
"net"
"time"
"github.com/goforj/web/webmiddleware"
"golang.org/x/time/rate"Update Controller.Routes in the same file to create the store and pass its middleware to the GET route. Keep any other routes you added to the controller.
// Routes applies one shared limiter to the user lookup route.
func (c *Controller) Routes() []web.Route {
store := webmiddleware.NewRateLimiterMemoryStoreWithConfig(
webmiddleware.RateLimiterMemoryStoreConfig{
Rate: rate.Every(time.Minute),
Burst: 1,
},
)
limit := webmiddleware.RateLimiterWithConfig(webmiddleware.RateLimiterConfig{
Store: store,
IdentifierExtractor: func(ctx web.Context) (string, error) {
host, _, err := net.SplitHostPort(ctx.Request().RemoteAddr)
return host, err
},
})
return []web.Route{
web.NewRoute(http.MethodGet, "/users/:id", c.Show, limit).
WithMiddlewareNames("webmiddleware.RateLimiter"),
}
}The store is created when the routes are composed, so requests share its token buckets. Burst: 1 permits the first request immediately. Each IP then earns one token per minute. All user IDs share that IP's bucket.
Key the limit by the connection's IP when clients connect directly. The default ctx.RealIP() can use forwarding headers, which require a trusted proxy configuration.
Verify the Response
List the registered routes from the Project root.
forj route:listThe route list includes /api/v1/users/:id with webmiddleware.RateLimiter. With forj dev running in another terminal, send two requests within a minute.
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3000/api/v1/users/42
# 200
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3000/api/v1/users/42
# 429Use your configured port if it differs from 3000. Wait a minute before repeating the check. Other requests from the same IP consume the same token.
Choose the Client Key and Store
Behind a reverse proxy, this recipe assigns one bucket to that proxy's connections. To limit by client IP, trust forwarding headers from your proxies and have each proxy replace untrusted values. For a per-account limit, derive the key from the authenticated account.
The memory store belongs to one process. A restart clears its buckets, and each replica has an independent allowance. For a limit shared across replicas, implement webmiddleware.RateLimiterStore with an atomic shared backend. A store adapter can use the cache library's rate-limit operation with a shared driver that supports it.
See Web rate limiting middleware for the store and handler contracts, or Middleware to apply a policy to a route group.