...
1 package admin
2
3 import (
4 "fmt"
5 "net/http"
6 "net/http/pprof"
7 "strings"
8 "time"
9
10 "github.com/prometheus/client_golang/prometheus/promhttp"
11 )
12
13 type handler struct {
14 promHandler http.Handler
15 enablePprof bool
16 ready *bool
17 }
18
19
20 func NewServer(addr string, enablePprof bool, ready *bool) *http.Server {
21 h := &handler{
22 promHandler: promhttp.Handler(),
23 enablePprof: enablePprof,
24 ready: ready,
25 }
26
27 return &http.Server{
28 Addr: addr,
29 Handler: h,
30 ReadHeaderTimeout: 15 * time.Second,
31 }
32 }
33
34 func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
35 debugPathPrefix := "/debug/pprof/"
36 if h.enablePprof && strings.HasPrefix(req.URL.Path, debugPathPrefix) {
37 switch req.URL.Path {
38 case fmt.Sprintf("%scmdline", debugPathPrefix):
39 pprof.Cmdline(w, req)
40 case fmt.Sprintf("%sprofile", debugPathPrefix):
41 pprof.Profile(w, req)
42 case fmt.Sprintf("%strace", debugPathPrefix):
43 pprof.Trace(w, req)
44 case fmt.Sprintf("%ssymbol", debugPathPrefix):
45 pprof.Symbol(w, req)
46 default:
47 pprof.Index(w, req)
48 }
49 return
50 }
51 switch req.URL.Path {
52 case "/metrics":
53 h.promHandler.ServeHTTP(w, req)
54 case "/ping":
55 h.servePing(w)
56 case "/ready":
57 h.serveReady(w)
58 default:
59 http.NotFound(w, req)
60 }
61 }
62
63 func (h *handler) servePing(w http.ResponseWriter) {
64 w.Write([]byte("pong\n"))
65 }
66
67 func (h *handler) serveReady(w http.ResponseWriter) {
68 if *h.ready {
69 w.Write([]byte("ok\n"))
70 } else {
71 w.WriteHeader(http.StatusInternalServerError)
72 w.Write([]byte("not ready\n"))
73 }
74 }
75
View as plain text