-
Notifications
You must be signed in to change notification settings - Fork 0
/
debugserver.go
71 lines (64 loc) · 1.56 KB
/
debugserver.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
package httpsimple
import (
"context"
"expvar"
"fmt"
"net"
"net/http"
"net/http/pprof"
"sync"
"sync/atomic"
"github.com/cresta/zapctx"
)
type DebugServer struct {
http.Server
ListenAddr string
Logger *zapctx.Logger
listener atomic.Value
mu sync.Mutex
}
func (d *DebugServer) Close() error {
d.mu.Lock()
defer d.mu.Unlock()
l := d.listener.Load()
if l == nil {
return nil
}
err := l.(net.Listener).Close()
d.Logger.IfErr(err).Warn(context.Background(), "unable to close debug server")
return err
}
func (d *DebugServer) Setup() error {
d.mu.Lock()
defer d.mu.Unlock()
if d.ListenAddr == "" || d.ListenAddr == "-" {
return nil
}
m := http.NewServeMux()
m.HandleFunc("/debug/pprof/", pprof.Index)
m.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
m.HandleFunc("/debug/pprof/profile", pprof.Profile)
m.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
m.HandleFunc("/debug/pprof/trace", pprof.Trace)
m.Handle("/debug/vars", expvar.Handler())
d.Handler = m
ln, err := net.Listen("tcp", d.ListenAddr)
if err != nil {
return fmt.Errorf("unable to listen to %s: %w", d.ListenAddr, err)
}
d.listener.Store(ln)
return nil
}
func (d *DebugServer) Start() error {
l := d.listener.Load()
if l == nil {
d.Logger.Info(context.Background(), "no listen address set. Not running debug server")
return nil
}
serveErr := d.Serve(l.(net.Listener))
if serveErr != http.ErrServerClosed {
d.Logger.IfErr(serveErr).Error(context.Background(), "debug server existed")
}
d.Logger.Info(context.Background(), "debug server finished")
return nil
}