Created
October 21, 2015 15:05
-
-
Save sergio-fry/330d1171494ade0d8011 to your computer and use it in GitHub Desktop.
Go HTTP limit connections
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
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