/
middleware.go
110 lines (96 loc) · 2.3 KB
/
middleware.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package server
import (
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/labstack/echo/v4"
)
/*
TODO: Use sync/atomic instead of mutex
*/
type sysStats struct {
CurrentMemAlloc uint64 `json:"current_memory"`
SysReserved uint64 `json:"sys_reserved"`
HeapLiveObjects uint64 `json:"heap_live_objects"`
GCRuns uint32 `json:"gc_runs"`
LastGC uint64 `json:"last_gc_in_ns"`
}
type requestors struct {
Requests uint32 `json:"processed_requests"`
UserAgents []string `json:"uniq_user_agents"`
}
func (r *requestors) addUserAgent(ua string) {
for _, nua := range r.UserAgents {
if nua == ua {
return
}
}
r.UserAgents = append(r.UserAgents, ua)
}
type stats struct {
System sysStats `json:"system"`
BootTime time.Time `json:"serving_since"`
Uptime string `json:"uptime"`
Requestors requestors `json:"request_stats"`
mtx sync.RWMutex
}
func newStats() *stats {
return &stats{
BootTime: time.Now(),
}
}
func (s *stats) midProcess(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if err := next(c); err != nil {
c.Error(err)
}
s.mtx.Lock()
defer s.mtx.Unlock()
atomic.AddUint32(&s.Requestors.Requests, 1)
r := c.Request()
ua := r.UserAgent()
s.Requestors.addUserAgent(ua)
if len(ua) > 50 {
ua = ua[:50]
}
logger.Debugf("[%s %s] [%s...] -> %d",
r.Method, r.URL.Path, ua, c.Response().Status)
return nil
}
}
func (s *stats) current() stats {
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
st := sysStats{
CurrentMemAlloc: ms.Alloc,
SysReserved: ms.Sys,
HeapLiveObjects: ms.Mallocs - ms.Frees,
GCRuns: ms.NumGC,
LastGC: ms.LastGC,
}
return stats{
System: st,
BootTime: s.BootTime,
Requestors: s.Requestors,
Uptime: time.Now().Sub(s.BootTime).String(),
}
}
// @Summary Statistics
// @Description Some statistics about this API
// @Produce json
// @Success 200 {object} server.stats "Some stats"
// @tags Others
// @Router /stats [GET]
func (s *stats) HandleStats(c echo.Context) error {
s.mtx.RLock()
defer s.mtx.RUnlock()
return c.JSON(200, s.current())
}
// -----
func midContactHeader(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Response().Header().Set("Contact-Me", "nicovillanueva@pm.me")
return next(c)
}
}