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

Implement rate-limiting from HTTP handler (e.g. by request payload) #42

Merged
merged 1 commit into from
Aug 23, 2024

Conversation

VojtechVitek
Copy link
Contributor

@VojtechVitek VojtechVitek commented Aug 23, 2024

Add support to rate-limit by custom key from HTTP handler (e.g. by request payload fields)

// Rate-limiter for login endpoint.
loginRateLimiter := httprate.NewRateLimiter(5, time.Minute)

r.Post("/login", func(w http.ResponseWriter, r *http.Request) {
	var payload struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}
	err := json.NewDecoder(r.Body).Decode(&payload)
	if err != nil || payload.Username == "" || payload.Password == "" {
		w.WriteHeader(400)
		return
	}

	// Rate-limit login at 5 req/min.
	if loginRateLimiter.OnLimit(w, r, payload.Username) {
		return
	}

	w.Write([]byte("login at 5 req/min\n"))
})

Copy link

Benchmark Results

goos: linux
goarch: amd64
pkg: github.com/go-chi/httprate
cpu: AMD EPYC 7763 64-Core Processor                
               │ master.txt  │            pr.txt             │
               │   sec/op    │   sec/op     vs base          │
LocalCounter-4   19.72m ± 1%   19.77m ± 1%  ~ (p=0.280 n=10)

               │  master.txt  │             pr.txt             │
               │     B/op     │     B/op      vs base          │
LocalCounter-4   2.831Mi ± 0%   2.834Mi ± 0%  ~ (p=0.218 n=10)

               │ master.txt  │            pr.txt             │
               │  allocs/op  │  allocs/op   vs base          │
LocalCounter-4   121.4k ± 0%   121.5k ± 0%  ~ (p=0.280 n=10)

@VojtechVitek VojtechVitek merged commit 80029e2 into master Aug 23, 2024
3 checks passed
@VojtechVitek VojtechVitek deleted the 7BkzJrtN branch August 23, 2024 12:37
VojtechVitek added a commit that referenced this pull request Aug 23, 2024
So users pass *http.RateLimiter (or save in their server struct) and use
the new .OnLimit() feature from #42.
VojtechVitek added a commit that referenced this pull request Aug 23, 2024
So users pass *http.RateLimiter (or save in their server struct) and use
the new .OnLimit() feature from #42.
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

Successfully merging this pull request may close these issues.

2 participants