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

Alex Mathew picture Alex Mathew · Mar 25, 2014 · Viewed 13.1k times · Source

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.

Answer

Ankit Arora picture Ankit Arora · May 22, 2016

You can use the netutil.LimitListener function to wrap around net.Listener if you don't want to implement your own wrapper:-

connectionCount := 20

l, err := net.Listen("tcp", ":8000")

if err != nil {
    log.Fatalf("Listen: %v", err)
}

defer l.Close()

l = netutil.LimitListener(l, connectionCount)

log.Fatal(http.Serve(l, nil))