Skip to content

Instantly share code, notes, and snippets.

@sergio-fry
Created October 21, 2015 15:05
Show Gist options
  • Save sergio-fry/330d1171494ade0d8011 to your computer and use it in GitHub Desktop.
Save sergio-fry/330d1171494ade0d8011 to your computer and use it in GitHub Desktop.
Go HTTP limit connections
func limitConnections(handler func(w http.ResponseWriter, r *http.Request), max_connections int) func(w http.ResponseWriter, r *http. Request) {
connections := make(chan bool, max_connections)
for i := 0; i < max_connections; i++ {
connections <- true
}
return func(w http.ResponseWriter, r *http.Request) {
select {
case <-connections:
defer func() { connections <- true }()
handler(w, r)
default:
http.Error(w, "Too many connections", 429)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment