go, get net/http connection count
var activeConnections int32func 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)} }