We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
It'd be nice to provide a simple HTTP middleware to avoid the boilerplate of adding the headers.
The text was updated successfully, but these errors were encountered:
@fproulx-eoscanada middlewares:
func authorizeMiddleware(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := context.WithValue(r.Context(), "user_id", "user-12345") next(w, r.WithContext(ctx)) } } func limiterMiddleware(rateLimiter *redis_rate.Limiter, limit int64, next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { userID := r.Context().Value("user_id").(string) rate, delay, allowed := rateLimiter.AllowMinute(userID, limit) if !allowed { h := w.Header() h.Set("X-RateLimit-Limit", strconv.FormatInt(limit, 10)) h.Set("X-RateLimit-Remaining", strconv.FormatInt(limit-rate, 10)) delaySec := int64(delay / time.Second) h.Set("X-RateLimit-Delay", strconv.FormatInt(delaySec, 10)) http.Error(w, "API rate limit exceeded.", 429) buf := new(bytes.Buffer) buf.WriteByte('\n') fmt.Fprintf(buf, "Current rate: %d\n", rate) fmt.Fprintf(buf, "Delay: %s\n", delay) fmt.Fprintf(buf, "Allowed: %v\n", allowed) fmt.Fprintf(buf, "Rate limit remaining: %s\n", strconv.FormatInt(limit-rate, 10)) buf.WriteTo(w) return } next(w, r) } } func handler(w http.ResponseWriter, _ *http.Request) { fmt.Fprintf(w, "Hello world!\n") }
func main:
redisClient := redis.NewClient(...) limiter := redis_rate.NewLimiter(redisClient) limit := int64(5) http.HandleFunc("/", authorizeMiddleware(limiterMiddleware(limiter, limit, handler))) log.Fatal(http.ListenAndServe("localhost:8820", nil))
Sorry, something went wrong.
No branches or pull requests
It'd be nice to provide a simple HTTP middleware to avoid the boilerplate of adding the headers.
The text was updated successfully, but these errors were encountered: