Skip to content
New issue

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

Add HTTP middleware #21

Open
fproulx-dfuse opened this issue Aug 21, 2019 · 1 comment
Open

Add HTTP middleware #21

fproulx-dfuse opened this issue Aug 21, 2019 · 1 comment

Comments

@fproulx-dfuse
Copy link

It'd be nice to provide a simple HTTP middleware to avoid the boilerplate of adding the headers.

@sergolius
Copy link

@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))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants