-
Notifications
You must be signed in to change notification settings - Fork 38
/
statsviz.go
51 lines (46 loc) · 1.13 KB
/
statsviz.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
package middleware
import (
"runtime"
"time"
"github.com/arl/statsviz"
"github.com/fasthttp/websocket"
"github.com/valyala/fasthttp/fasthttpadaptor"
"github.com/xiusin/pine"
)
func StatesViz(app *pine.Application) pine.Handler {
type stats struct {
Mem runtime.MemStats
NumGoroutine int
}
upgrade := websocket.FastHTTPUpgrader{}
indexHandler := fasthttpadaptor.NewFastHTTPHandler(statsviz.Index)
app.GET("/debug/statsviz/*filepath", func(ctx *pine.Context) {
if ctx.Params().Get("filepath") == "ws" {
err := upgrade.Upgrade(ctx.RequestCtx, func(ws *websocket.Conn) {
defer ws.Close()
tick := time.NewTicker(time.Second)
defer tick.Stop()
var stats stats
for range tick.C {
runtime.ReadMemStats(&stats.Mem)
stats.NumGoroutine = runtime.NumGoroutine()
if err := ws.WriteJSON(stats); err != nil {
pine.Logger().Print(err)
break
}
}
})
if err != nil {
if _, ok := err.(websocket.HandshakeError); ok {
pine.Logger().Error(err)
}
return
}
} else {
indexHandler(ctx.RequestCtx)
}
})
return func(ctx *pine.Context) {
ctx.Next()
}
}