有没有办法在主机上获取所有打开的 http 连接?
Is there a way to get all the open http connections on a host in go?
我有一个网络服务器。有没有办法让我获得该主机上所有打开的 http 连接?
创建一个类型来记录打开的连接以响应服务器 connection state 更改:
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 以使用 method value:
var cw ConnectionWatcher
s := &http.Server{
ConnState: cw.OnStateChange
}
使用 ListenAndServe, Serve 或这些方法的 TLS 变体启动服务器。
根据应用程序正在执行的操作,您可能希望在检查连接时锁定 ConnectionWatcher.mu。
我有一个网络服务器。有没有办法让我获得该主机上所有打开的 http 连接?
创建一个类型来记录打开的连接以响应服务器 connection state 更改:
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 以使用 method value:
var cw ConnectionWatcher
s := &http.Server{
ConnState: cw.OnStateChange
}
使用 ListenAndServe, Serve 或这些方法的 TLS 变体启动服务器。
根据应用程序正在执行的操作,您可能希望在检查连接时锁定 ConnectionWatcher.mu。