go get net/http connections count, using middleware

go, get net/http connection count

 

var activeConnections int32

func handler(w http.ResponseWriter, r *http.Request) {
    atomic.AddInt32(&activeConnections, 1)
    defer atomic.AddInt32(&activeConnections, -1)
    
    // 处理请求逻辑
}

func main() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Active connections: %d", atomic.LoadInt32(&activeConnections))
    })
    http.ListenAndServe(":8080", nil)
}

using middleware:

func wrapHandler(handler http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        atomic.AddInt32(&activeConnections, 1)
        defer atomic.AddInt32(&activeConnections, -1)
        handler(w, r)
    }
}

 

posted @ 2025-10-06 17:34  calochCN  阅读(7)  评论(0)    收藏  举报