登录
首页 >  Golang >  Go问答

如何在Go语言中检索所有打开的HTTP连接?

来源:stackoverflow

时间:2024-03-13 09:00:25 147浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《如何在Go语言中检索所有打开的HTTP连接?》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我有一个 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
}

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

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

Run it on the playground

终于介绍完啦!小伙伴们,这篇关于《如何在Go语言中检索所有打开的HTTP连接?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>