1

我有一个 Go 网络服务器。有没有一种方法可以让我在该主机上获得所有打开的 http 连接?

4

1 回答 1

3

创建一个类型来记录打开的连接以响应服务器连接状态的变化:

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
}

配置 net.Server 以使用方法值

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

使用ListenAndServeServe或这些方法的 TLS 变体启动服务器。

根据应用程序正在执行的操作,您可能希望在检查连接时锁定 ConnectionWatcher.mu。

在操场上运行它

于 2020-07-07T01:53:05.090 回答