...

Source file src/github.com/go-chi/chi/middleware/profiler.go

Documentation: github.com/go-chi/chi/middleware

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

View as plain text