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

后端 未结 3 929
遇见更好的自我
遇见更好的自我 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:35

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

提交回复
热议问题