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) } }
浙公网安备 33010602011771号