generated from bool64/go-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mux.go
60 lines (46 loc) · 1.29 KB
/
mux.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 debug
import (
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
type page struct {
link, title string
}
// Mux serves debug tools.
type Mux struct {
*chi.Mux
Prefix string
pages []page
body []byte
}
// NewMux creates a new router for debug tools.
func NewMux(prefix string) *Mux {
debugRouter, ok := middleware.Profiler().(*chi.Mux)
if !ok {
panic("BUG: failed to assert middleware.Profiler().(*chi.Mux)")
}
r := &Mux{Prefix: prefix}
r.Mux = debugRouter
r.Get("/", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf8")
_, err := w.Write(r.body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
r.AddLink("pprof", "Profiling")
return r
}
func (r *Mux) buildIndex() {
r.body = []byte(`<!DOCTYPE html><html><head><title>Debug Tools</title><base href="` + r.Prefix + `/" /></head><h2>Debug Tools</h2><ul>`)
for _, p := range r.pages {
r.body = append(r.body, []byte(`<li><a href="`+p.link+`">`+p.title+`</a></li>`)...)
}
r.body = append(r.body, []byte(`</ul></html>`)...)
}
// AddLink adds a link to the index page of debug tools.
func (r *Mux) AddLink(link, title string) {
r.pages = append(r.pages, page{link: link, title: title})
r.buildIndex()
}