I am trying to implement an HTTP Server in Golang.
My problem is, I have to limit the maximum active connections count at any particular time to 20.
With the help of channel you can limit the count of active connections.
1.At the server start up time create a channel and put equal number of limit count(in your case 20) values into the channel.
2.Remove one value from the channel while serving one request.
One example from the web
type limitHandler struct {
connc chan struct{}
handler http.Handler
}
func (h *limitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
select {
case <-connc:
h.handler.ServeHTTP(w, req)
connc <- struct{}{}
default:
http.Error(w, "503 too busy", StatusServiceUnavailable)
}
}
func NewLimitHandler(maxConns int, handler http.Handler) http.Handler {
h := &limitHandler{
connc: make(chan struct{}, maxConns),
handler: handler,
}
for i := 0; i < maxConns; i++ {
connc <- struct{}{}
}
return h
}