-
Notifications
You must be signed in to change notification settings - Fork 127
/
debug.go
73 lines (63 loc) · 1.95 KB
/
debug.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
package debug
import (
"net/http"
"net/http/pprof"
"path"
"strings"
rmux "github.com/go-kratos/gateway/router/mux"
"github.com/go-kratos/kratos/v2/log"
"github.com/gorilla/mux"
)
const (
_debugPrefix = "/debug"
)
var globalService = &debugService{
handlers: map[string]http.HandlerFunc{
"/debug/ping": func(rw http.ResponseWriter, r *http.Request) {},
"/debug/pprof/": pprof.Index,
"/debug/pprof/cmdline": pprof.Cmdline,
"/debug/pprof/profile": pprof.Profile,
"/debug/pprof/symbol": pprof.Symbol,
"/debug/pprof/trace": pprof.Trace,
"/debug/pprof/allocs": pprof.Handler("allocs").ServeHTTP,
"/debug/pprof/block": pprof.Handler("block").ServeHTTP,
"/debug/pprof/goroutine": pprof.Handler("goroutine").ServeHTTP,
"/debug/pprof/heap": pprof.Handler("heap").ServeHTTP,
"/debug/pprof/mutex": pprof.Handler("mutex").ServeHTTP,
"/debug/pprof/threadcreate": pprof.Handler("threadcreate").ServeHTTP,
},
mux: mux.NewRouter(),
}
func Register(name string, debuggable Debuggable) {
globalService.Register(name, debuggable)
}
func MashupWithDebugHandler(origin http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if strings.HasPrefix(req.URL.Path, _debugPrefix) {
rmux.ProtectedHandler(globalService).ServeHTTP(w, req)
return
}
origin.ServeHTTP(w, req)
})
}
type Debuggable interface {
DebugHandler() http.Handler
}
type debugService struct {
handlers map[string]http.HandlerFunc
mux *mux.Router
}
func (d *debugService) ServeHTTP(w http.ResponseWriter, req *http.Request) {
for path, handler := range d.handlers {
if path == req.URL.Path {
handler(w, req)
return
}
}
d.mux.ServeHTTP(w, req)
}
func (d *debugService) Register(name string, debuggable Debuggable) {
path := path.Join(_debugPrefix, name)
d.mux.PathPrefix(path).Handler(debuggable.DebugHandler())
log.Infof("register debug: %s", path)
}