-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoints.go
60 lines (50 loc) · 1.47 KB
/
endpoints.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
package http_profiling
import (
"fmt"
"github.com/valyala/fasthttp"
"runtime/pprof"
"time"
)
func AuthMiddleware(h fasthttp.RequestHandler, token string) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
tokenHeader := ctx.Request.Header.Peek("X-Profiling-Token")
if len(tokenHeader) == 0 {
ctx.SetStatusCode(400)
return
}
if string(tokenHeader) != token {
ctx.SetStatusCode(401)
return
}
h(ctx)
}
}
func HandleCpuProfiling(ctx *fasthttp.RequestCtx) {
args := ctx.Request.URI().QueryArgs()
timeSec := args.GetUintOrZero("time")
if timeSec == 0 {
ctx.SetStatusCode(400)
return
}
ctx.Response.Header.Set("Content-Type", "application/octet-stream")
ctx.Response.Header.Set("X-Go-Pprof", "1")
ctx.Response.Header.Set("Content-Disposition", "attachment; filename=\"cpu.prof\"")
if err := pprof.StartCPUProfile(ctx); err != nil {
ctx.SetStatusCode(500)
_, _ = fmt.Fprintf(ctx, "could not start CPU profile: %s", err)
return
}
timer := time.NewTimer(time.Second * time.Duration(timeSec))
<-timer.C
pprof.StopCPUProfile()
}
func HandleMemProfiling(ctx *fasthttp.RequestCtx) {
ctx.Response.Header.Set("Content-Type", "application/octet-stream")
ctx.Response.Header.Set("X-Go-Pprof", "1")
ctx.Response.Header.Set("Content-Disposition", "attachment; filename=\"mem.prof\"")
if err := pprof.WriteHeapProfile(ctx); err != nil {
ctx.SetStatusCode(500)
_, _ = fmt.Fprintf(ctx, "could not write memory profile: %s", err)
return
}
}