Search code examples
gohttpserver

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


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.


Solution

  • 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))