Vibe-guided bskyoauth and custom repo example code in Golang 馃 probably not safe to use in prod
1package bskyoauth
2
3import (
4 "net/http"
5 "time"
6
7 "golang.org/x/time/rate"
8
9 internalhttp "github.com/shindakun/bskyoauth/internal/http"
10)
11
12// RateLimiter provides IP-based rate limiting for HTTP endpoints.
13type RateLimiter struct {
14 limiter *internalhttp.RateLimiter
15}
16
17// NewRateLimiter creates a new rate limiter.
18// r is the rate (requests per second), b is the burst size.
19// Example: NewRateLimiter(5, 10) allows 5 requests/second with burst of 10.
20func NewRateLimiter(r rate.Limit, b int) *RateLimiter {
21 loggerGetter := func(req *http.Request) internalhttp.Logger {
22 return LoggerFromContext(req.Context())
23 }
24 return &RateLimiter{
25 limiter: internalhttp.NewRateLimiter(r, b, loggerGetter),
26 }
27}
28
29// Middleware returns an HTTP middleware that applies rate limiting.
30func (rl *RateLimiter) Middleware(next http.HandlerFunc) http.HandlerFunc {
31 return rl.limiter.Middleware(next)
32}
33
34// Cleanup removes idle rate limiters to prevent memory leaks.
35// Should be called periodically in a goroutine.
36func (rl *RateLimiter) Cleanup(maxAge time.Duration) {
37 rl.limiter.Cleanup(maxAge, Logger)
38}
39
40// StartCleanup starts a background goroutine that periodically cleans up old limiters.
41func (rl *RateLimiter) StartCleanup(interval, maxAge time.Duration) {
42 rl.limiter.StartCleanup(interval, maxAge, Logger)
43}