I have written a small wrapper function which use counting semaphore concept to limit number of connections to a particular handler (as this handler is resource consuming). Below is the code which achieve the same.
func LimitNumClients(f http.HandlerFunc, maxClients int) http.HandlerFunc {
// Counting semaphore using a buffered channel
sema := make(chan struct{}, maxClients)
return func(w http.ResponseWriter, req *http.Request) {
sema <- struct{}{}
defer func() { <-sema }()
f(w, req)
}
}
And then wrapper it up in the handler as below
Route{
"Test",
"GET",
/test,
LimitNumClients(testhandler, 5),
},
Now I want to reply back with 501 error when the client limit is reached for any new connection. How to achieve the same.