Search code examples
gogo-http

Is there a way to get all the open http connections on a host in go?


I have a go webserver. Is there a way where I can get all the open http connections on that host?


Solution

  • Create a type to record open connections in response to server connection state changes:

    type ConnectionWatcher struct {
        // mu protects remaining fields
        mu sync.Mutex
    
        // open connections are keys in the map
        m  map[net.Conn]struct{}
    }
    
    // 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.mu.Lock()
            if cw.m == nil {
                cw.m = make(map[net.Conn]struct{})
            }
            cw.m[conn] = struct{}{}
            cw.mu.Unlock()
        case http.StateHijacked, http.StateClosed:
            cw.mu.Lock()
            delete(cw.m, conn)
            cw.mu.Unlock()
        }
    }
    
    // Connections returns the open connections at the time
    // the call. 
    func (cw *ConnectionWatcher) Connections() []net.Conn {
        var result []net.Conn
        cw.mu.Lock()
        for conn := range cw.m {
            result = append(result, conn)
        }
        cw.mu.Unlock()
        return result
    }
    

    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.

    Depending on what the application is doing, you may want to lock ConnectionWatcher.mu while examining the connections.

    Run it on the playground.