mattes
mattes

Reputation: 9429

How to get number of idle and "active" connections in Go?

Assuming I have a regular HTTP Server in Go. How can I get the currently idle and active TCP connections?

httpServer := &http.Server{
    Handler: newHandler123(),
}

l, err := net.Listen("tcp", ":8080")
if err != nil {
    log.Fatal(err)
}

err = httpServer.Serve(l)
if err != nil {
    log.Fatal(err)
}

Upvotes: 9

Views: 5516

Answers (1)

Thundercat
Thundercat

Reputation: 120951

Create a type to count the number open connections in response to server connection state changes:

type ConnectionWatcher struct {
    n int64
}

// OnStateChange records open connections in response to connection
// state changes. Set net/http Server.ConnState to this method
// as value.
func (cw *ConnectionWatcher) OnStateChange(conn net.Conn, state http.ConnState) {
    switch state {
    case http.StateNew:
        cw.Add(1)
    case http.StateHijacked, http.StateClosed:
        cw.Add(-1)
    }
}

// Count returns the number of connections at the time
// the call.    
func (cw *ConnectionWatcher) Count() int {
    return int(atomic.LoadInt64(&cw.n))
}

// Add adds c to the number of active connections. 
func (cw *ConnectionWatcher) Add(c int64) {
    atomic.AddInt64(&cw.n, c)
}

Configure the net.Server to use the method value:

var cw ConnectionWatcher
s := &http.Server{
   ConnState: cw.OnStateChange
}

Start the server using ListenAndServe, Serve or the TLS variants of these methods.

Call cw.Count() to get the number of open connections.

Run it on the playground.

This code does not monitor connections hijacked from the net/http server. Most notably, WebSocket connections are hijacked from the server. To monitor WebSocket connections, the application should call cw.Add(1) on successful upgrade to the WebSocket protocol and cw.Add(-1) after closing the WebSocket connection.

Upvotes: 12

Related Questions