-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats.go
executable file
·86 lines (73 loc) · 1.8 KB
/
stats.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package stats
import (
"encoding/json"
"fmt"
"github.com/zc310/fs/middleware"
"os"
"github.com/valyala/fasthttp"
"strings"
"sync"
"time"
)
type Stats struct {
mu sync.RWMutex `json:"-"`
Uptime time.Time `json:"-"`
Pid int `json:"-"`
ResponseCounts map[string]int64 `json:"-"`
Path string `json:"path"`
}
type Data struct {
UpTime string `json:"uptime"`
UpTimeSec float64 `json:"uptime_sec"`
ResponseCounts map[string]int64 `json:"count"`
TotalCount int64 `json:"total_count"`
}
func (p *Stats) Init(c *middleware.Config) error {
p.Uptime = time.Now()
p.ResponseCounts = map[string]int64{}
p.Pid = os.Getegid()
if p.Path == "" {
p.Path = "/_stats"
}
if !strings.HasPrefix(p.Path, "/") {
p.Path = "/" + p.Path
}
c.Router.GET(p.Path, p.Handler())
return nil
}
func (p *Stats) UnInit() {}
func (p *Stats) Data() *Data {
now := time.Now()
p.mu.RLock()
uptime := now.Sub(p.Uptime)
r := &Data{}
count := int64(0)
responseCounts := make(map[string]int64)
for path, current := range p.ResponseCounts {
responseCounts[path] = current
count += current
}
p.mu.RUnlock()
r.UpTime = uptime.String()
r.UpTimeSec = uptime.Seconds()
r.TotalCount = count
r.ResponseCounts = responseCounts
return r
}
func (p *Stats) Process(h fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
h(ctx)
p.mu.Lock()
p.ResponseCounts[string(ctx.Path())]++
p.mu.Unlock()
}
}
func (p *Stats) Handler() fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
ctx.SetContentType("application/json; charset=utf-8")
err := json.NewEncoder(ctx.Response.BodyWriter()).Encode(p.Data())
if err != nil {
fmt.Fprint(ctx, "{}\n")
}
}
}