Last active
October 21, 2015 15:07
-
-
Save sergio-fry/d07d4ec366ca2b9a0d0d to your computer and use it in GitHub Desktop.
Go HTTP limit rate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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