Skip to content

Instantly share code, notes, and snippets.

@sergio-fry
Last active October 21, 2015 15:07
Show Gist options
  • Save sergio-fry/d07d4ec366ca2b9a0d0d to your computer and use it in GitHub Desktop.
Save sergio-fry/d07d4ec366ca2b9a0d0d to your computer and use it in GitHub Desktop.
Go HTTP limit rate
import "github.com/beefsack/go-rate"
func limitRate(handler func(w http.ResponseWriter, r *http.Request), max_requests int, period time.Duration) func(w http.ResponseWriter, r * http.Request) {
rl := rate.New(max_requests, period)
return func(w http.ResponseWriter, r *http.Request) {
ok, _ := rl.Try()
if ok {
handler(w, r)
} else {
http.Error(w, "Too many requests", 429)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment