How to limit the connections count of an HTTP Server implemented in Go?

后端 未结 3 932
遇见更好的自我
遇见更好的自我 2021-02-01 08:11

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.

3条回答
  •  余生分开走
    2021-02-01 08:21

    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
    }
    

提交回复
热议问题