You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

profiler.go 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package middleware
  2. import (
  3. "expvar"
  4. "fmt"
  5. "net/http"
  6. "net/http/pprof"
  7. "github.com/go-chi/chi/v5"
  8. )
  9. // Profiler is a convenient subrouter used for mounting net/http/pprof. ie.
  10. //
  11. // func MyService() http.Handler {
  12. // r := chi.NewRouter()
  13. // // ..middlewares
  14. // r.Mount("/debug", middleware.Profiler())
  15. // // ..routes
  16. // return r
  17. // }
  18. func Profiler() http.Handler {
  19. r := chi.NewRouter()
  20. r.Use(NoCache)
  21. r.Get("/", func(w http.ResponseWriter, r *http.Request) {
  22. http.Redirect(w, r, r.RequestURI+"/pprof/", http.StatusMovedPermanently)
  23. })
  24. r.HandleFunc("/pprof", func(w http.ResponseWriter, r *http.Request) {
  25. http.Redirect(w, r, r.RequestURI+"/", http.StatusMovedPermanently)
  26. })
  27. r.HandleFunc("/pprof/*", pprof.Index)
  28. r.HandleFunc("/pprof/cmdline", pprof.Cmdline)
  29. r.HandleFunc("/pprof/profile", pprof.Profile)
  30. r.HandleFunc("/pprof/symbol", pprof.Symbol)
  31. r.HandleFunc("/pprof/trace", pprof.Trace)
  32. r.HandleFunc("/vars", expVars)
  33. r.Handle("/pprof/goroutine", pprof.Handler("goroutine"))
  34. r.Handle("/pprof/threadcreate", pprof.Handler("threadcreate"))
  35. r.Handle("/pprof/mutex", pprof.Handler("mutex"))
  36. r.Handle("/pprof/heap", pprof.Handler("heap"))
  37. r.Handle("/pprof/block", pprof.Handler("block"))
  38. r.Handle("/pprof/allocs", pprof.Handler("allocs"))
  39. return r
  40. }
  41. // Replicated from expvar.go as not public.
  42. func expVars(w http.ResponseWriter, r *http.Request) {
  43. first := true
  44. w.Header().Set("Content-Type", "application/json")
  45. fmt.Fprintf(w, "{\n")
  46. expvar.Do(func(kv expvar.KeyValue) {
  47. if !first {
  48. fmt.Fprintf(w, ",\n")
  49. }
  50. first = false
  51. fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
  52. })
  53. fmt.Fprintf(w, "\n}\n")
  54. }