profiler.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package server
  2. import (
  3. "expvar"
  4. "fmt"
  5. "net/http"
  6. "net/http/pprof"
  7. "github.com/gorilla/mux"
  8. )
  9. const debugPathPrefix = "/debug/"
  10. func profilerSetup(mainRouter *mux.Router) {
  11. var r = mainRouter.PathPrefix(debugPathPrefix).Subrouter()
  12. r.HandleFunc("/vars", expVars)
  13. r.HandleFunc("/pprof/", pprof.Index)
  14. r.HandleFunc("/pprof/cmdline", pprof.Cmdline)
  15. r.HandleFunc("/pprof/profile", pprof.Profile)
  16. r.HandleFunc("/pprof/symbol", pprof.Symbol)
  17. r.HandleFunc("/pprof/trace", pprof.Trace)
  18. r.HandleFunc("/pprof/{name}", handlePprof)
  19. }
  20. func handlePprof(w http.ResponseWriter, r *http.Request) {
  21. var name string
  22. if vars := mux.Vars(r); vars != nil {
  23. name = vars["name"]
  24. }
  25. pprof.Handler(name).ServeHTTP(w, r)
  26. }
  27. // Replicated from expvar.go as not public.
  28. func expVars(w http.ResponseWriter, r *http.Request) {
  29. first := true
  30. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  31. fmt.Fprintln(w, "{")
  32. expvar.Do(func(kv expvar.KeyValue) {
  33. if !first {
  34. fmt.Fprintln(w, ",")
  35. }
  36. first = false
  37. fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
  38. })
  39. fmt.Fprintln(w, "\n}")
  40. }