debug.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package snap
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "expvar"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "net/http/pprof"
  10. "runtime"
  11. "github.com/gorilla/mux"
  12. )
  13. func stackHandler(w http.ResponseWriter, r *http.Request) {
  14. http.Redirect(w, r, "/sovereign/debug/pprof/goroutine?debug=2", http.StatusSeeOther)
  15. }
  16. // copy pasted from http://golang.org/src/expvar/expvar.go#L308
  17. func varsHandler(w http.ResponseWriter, r *http.Request) {
  18. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  19. buf := make([]byte, 0, 16384)
  20. body := bytes.NewBuffer(buf)
  21. fmt.Fprintf(body, "{")
  22. expvar.Do(func(kv expvar.KeyValue) {
  23. fmt.Fprintf(body, "%q: %s,", kv.Key, kv.Value)
  24. })
  25. fmt.Fprintf(body, "%q: %d", "NumGoRoutines", runtime.NumGoroutine())
  26. fmt.Fprintf(body, "}")
  27. var prettyJSON bytes.Buffer
  28. err := json.Indent(&prettyJSON, body.Bytes(), "", " ")
  29. if err != nil {
  30. log.Println(err, string(body.Bytes()))
  31. }
  32. w.Write(prettyJSON.Bytes())
  33. }
  34. func setupDebugHandler(r *mux.Router) {
  35. r.HandleFunc("/stack", stackHandler)
  36. r.HandleFunc("/vars", varsHandler)
  37. r.HandleFunc("/pprof/", http.HandlerFunc(pprof.Index))
  38. r.HandleFunc("/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
  39. r.HandleFunc("/pprof/profile", http.HandlerFunc(pprof.Profile))
  40. r.HandleFunc("/pprof/symbol", http.HandlerFunc(pprof.Symbol))
  41. r.HandleFunc("/pprof/trace", http.HandlerFunc(pprof.Trace))
  42. r.HandleFunc("/pprof/goroutine", pprof.Handler("goroutine").ServeHTTP)
  43. r.HandleFunc("/pprof/allocs", pprof.Handler("allocs").ServeHTTP)
  44. r.HandleFunc("/pprof/block", pprof.Handler("block").ServeHTTP)
  45. r.HandleFunc("/pprof/heap", pprof.Handler("heap").ServeHTTP)
  46. r.HandleFunc("/pprof/mutex", pprof.Handler("mutex").ServeHTTP)
  47. }