Skip to content

Instantly share code, notes, and snippets.

@gedex
Last active April 17, 2016 06:20
Show Gist options
  • Save gedex/e7907318522ea4f15cf3870cfb6ec12a to your computer and use it in GitHub Desktop.
Save gedex/e7907318522ea4f15cf3870cfb6ec12a to your computer and use it in GitHub Desktop.
Max clients in net/http
package main
import (
"log"
"net/http"
"time"
)
func maxClientsHandler(maxClients int, timeout time.Duration, h http.Handler) http.Handler {
var reqCounter int
sema := make(chan struct{}, maxClients)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqCounter++
reqId := reqCounter
start := time.Now()
for {
select {
case sema <- struct{}{}:
defer func() { <-sema }()
log.Printf("Request %d processed\n", reqId)
h.ServeHTTP(w, r)
log.Printf("Request %d finished in %s\n", reqId, time.Now().Sub(start).String())
return
case <-time.After(timeout):
log.Printf("Timeout for request %d\n", reqId)
http.Error(w, "Timeout", http.StatusRequestTimeout)
return
}
}
})
}
func final(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Second * 2)
w.Write([]byte("OK"))
}
func main() {
finalHandler := http.HandlerFunc(final)
http.Handle("/", maxClientsHandler(3, time.Second*3, finalHandler))
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment