1
0

stats.go 795 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package middleware
  2. import (
  3. "sync/atomic"
  4. "github.com/gin-gonic/gin"
  5. )
  6. // HTTPStats 存储HTTP统计信息
  7. type HTTPStats struct {
  8. activeConnections int64
  9. }
  10. var globalStats = &HTTPStats{}
  11. // StatsMiddleware 统计中间件
  12. func StatsMiddleware() gin.HandlerFunc {
  13. return func(c *gin.Context) {
  14. // 增加活跃连接数
  15. atomic.AddInt64(&globalStats.activeConnections, 1)
  16. // 确保在请求结束时减少连接数
  17. defer func() {
  18. atomic.AddInt64(&globalStats.activeConnections, -1)
  19. }()
  20. c.Next()
  21. }
  22. }
  23. // StatsInfo 统计信息结构
  24. type StatsInfo struct {
  25. ActiveConnections int64 `json:"active_connections"`
  26. }
  27. // GetStats 获取统计信息
  28. func GetStats() StatsInfo {
  29. return StatsInfo{
  30. ActiveConnections: atomic.LoadInt64(&globalStats.activeConnections),
  31. }
  32. }