github.com/hellobchain/third_party@v0.0.0-20230331131523-deb0478a2e52/go-chi/chi/middleware/profiler.go (about)

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