// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package pprof serves via its HTTP server runtime profiling data // in the format expected by the pprof visualization tool. // // The package is typically only imported for the side effect of // registering its HTTP handlers. // The handled paths all begin with /debug/pprof/. // As of Go 1.22, all the paths must be requested with GET. // // To use pprof, link this package into your program: // // import _ "net/http/pprof" // // If your application is not already running an http server, you // need to start one. Add "net/http" and "log" to your imports and // the following code to your main function: // // go func() { // log.Println(http.ListenAndServe("localhost:6060", nil)) // }() // // By default, all the profiles listed in [runtime/pprof.Profile] are // available (via [Handler]), in addition to the [Cmdline], [Profile], [Symbol], // and [Trace] profiles defined in this package. // If you are not using DefaultServeMux, you will have to register handlers // with the mux you are using. // // # Parameters // // Parameters can be passed via GET query params: // // - debug=N (all profiles): response format: N = 0: binary (default), N > 0: plaintext // - gc=N (heap profile): N > 0: run a garbage collection cycle before profiling // - seconds=N (allocs, block, goroutine, heap, mutex, threadcreate profiles): return a delta profile // - seconds=N (cpu (profile), trace profiles): profile for the given duration // // # Usage examples // // Use the pprof tool to look at the heap profile: // // go tool pprof http://localhost:6060/debug/pprof/heap // // Or to look at a 30-second CPU profile: // // go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30 // // Or to look at the goroutine blocking profile, after calling // [runtime.SetBlockProfileRate] in your program: // // go tool pprof http://localhost:6060/debug/pprof/block // // Or to look at the holders of contended mutexes, after calling // [runtime.SetMutexProfileFraction] in your program: // // go tool pprof http://localhost:6060/debug/pprof/mutex // // The package also exports a handler that serves execution trace data // for the "go tool trace" command. To collect a 5-second execution trace: // // curl -o trace.out http://localhost:6060/debug/pprof/trace?seconds=5 // go tool trace trace.out // // To view all available profiles, open http://localhost:6060/debug/pprof/ // in your browser. // // For a study of the facility in action, visit // https://blog.golang.org/2011/06/profiling-go-programs.html.
package pprof import ( ) func init() { := "" if godebug.New("httpmuxgo121").Value() != "1" { = "GET " } http.HandleFunc(+"/debug/pprof/", Index) http.HandleFunc(+"/debug/pprof/cmdline", Cmdline) http.HandleFunc(+"/debug/pprof/profile", Profile) http.HandleFunc(+"/debug/pprof/symbol", Symbol) http.HandleFunc(+"/debug/pprof/trace", Trace) } // Cmdline responds with the running program's // command line, with arguments separated by NUL bytes. // The package initialization registers it as /debug/pprof/cmdline. func ( http.ResponseWriter, *http.Request) { .Header().Set("X-Content-Type-Options", "nosniff") .Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprint(, strings.Join(os.Args, "\x00")) } func sleep( *http.Request, time.Duration) { select { case <-time.After(): case <-.Context().Done(): } } func configureWriteDeadline( http.ResponseWriter, *http.Request, float64) { , := .Context().Value(http.ServerContextKey).(*http.Server) if && .WriteTimeout > 0 { := .WriteTimeout + time.Duration(*float64(time.Second)) := http.NewResponseController() .SetWriteDeadline(time.Now().Add()) } } func serveError( http.ResponseWriter, int, string) { .Header().Set("Content-Type", "text/plain; charset=utf-8") .Header().Set("X-Go-Pprof", "1") .Header().Del("Content-Disposition") .WriteHeader() fmt.Fprintln(, ) } // Profile responds with the pprof-formatted cpu profile. // Profiling lasts for duration specified in seconds GET parameter, or for 30 seconds if not specified. // The package initialization registers it as /debug/pprof/profile. func ( http.ResponseWriter, *http.Request) { .Header().Set("X-Content-Type-Options", "nosniff") , := strconv.ParseInt(.FormValue("seconds"), 10, 64) if <= 0 || != nil { = 30 } configureWriteDeadline(, , float64()) // Set Content Type assuming StartCPUProfile will work, // because if it does it starts writing. .Header().Set("Content-Type", "application/octet-stream") .Header().Set("Content-Disposition", `attachment; filename="profile"`) if := pprof.StartCPUProfile(); != nil { // StartCPUProfile failed, so no writes yet. serveError(, http.StatusInternalServerError, fmt.Sprintf("Could not enable CPU profiling: %s", )) return } sleep(, time.Duration()*time.Second) pprof.StopCPUProfile() } // Trace responds with the execution trace in binary form. // Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified. // The package initialization registers it as /debug/pprof/trace. func ( http.ResponseWriter, *http.Request) { .Header().Set("X-Content-Type-Options", "nosniff") , := strconv.ParseFloat(.FormValue("seconds"), 64) if <= 0 || != nil { = 1 } configureWriteDeadline(, , ) // Set Content Type assuming trace.Start will work, // because if it does it starts writing. .Header().Set("Content-Type", "application/octet-stream") .Header().Set("Content-Disposition", `attachment; filename="trace"`) if := trace.Start(); != nil { // trace.Start failed, so no writes yet. serveError(, http.StatusInternalServerError, fmt.Sprintf("Could not enable tracing: %s", )) return } sleep(, time.Duration(*float64(time.Second))) trace.Stop() } // Symbol looks up the program counters listed in the request, // responding with a table mapping program counters to function names. // The package initialization registers it as /debug/pprof/symbol. func ( http.ResponseWriter, *http.Request) { .Header().Set("X-Content-Type-Options", "nosniff") .Header().Set("Content-Type", "text/plain; charset=utf-8") // We have to read the whole POST body before // writing any output. Buffer the output here. var bytes.Buffer // We don't know how many symbols we have, but we // do have symbol information. Pprof only cares whether // this number is 0 (no symbols available) or > 0. fmt.Fprintf(&, "num_symbols: 1\n") var *bufio.Reader if .Method == "POST" { = bufio.NewReader(.Body) } else { = bufio.NewReader(strings.NewReader(.URL.RawQuery)) } for { , := .ReadSlice('+') if == nil { = [0 : len()-1] // trim + } , := strconv.ParseUint(string(), 0, 64) if != 0 { := runtime.FuncForPC(uintptr()) if != nil { fmt.Fprintf(&, "%#x %s\n", , .Name()) } } // Wait until here to check for err; the last // symbol will have an err because it doesn't end in +. if != nil { if != io.EOF { fmt.Fprintf(&, "reading request: %v\n", ) } break } } .Write(.Bytes()) } // Handler returns an HTTP handler that serves the named profile. // Available profiles can be found in [runtime/pprof.Profile]. func ( string) http.Handler { return handler() } type handler string func ( handler) ( http.ResponseWriter, *http.Request) { .Header().Set("X-Content-Type-Options", "nosniff") := pprof.Lookup(string()) if == nil { serveError(, http.StatusNotFound, "Unknown profile") return } if := .FormValue("seconds"); != "" { .serveDeltaProfile(, , , ) return } , := strconv.Atoi(.FormValue("gc")) if == "heap" && > 0 { runtime.GC() } , := strconv.Atoi(.FormValue("debug")) if != 0 { .Header().Set("Content-Type", "text/plain; charset=utf-8") } else { .Header().Set("Content-Type", "application/octet-stream") .Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, )) } .WriteTo(, ) } func ( handler) ( http.ResponseWriter, *http.Request, *pprof.Profile, string) { , := strconv.ParseInt(, 10, 64) if != nil || <= 0 { serveError(, http.StatusBadRequest, `invalid value for "seconds" - must be a positive integer`) return } // 'name' should be a key in profileSupportsDelta. if !profileSupportsDelta[] { serveError(, http.StatusBadRequest, `"seconds" parameter is not supported for this profile type`) return } configureWriteDeadline(, , float64()) , := strconv.Atoi(.FormValue("debug")) if != 0 { serveError(, http.StatusBadRequest, "seconds and debug params are incompatible") return } , := collectProfile() if != nil { serveError(, http.StatusInternalServerError, "failed to collect profile") return } := time.NewTimer(time.Duration() * time.Second) defer .Stop() select { case <-.Context().Done(): := .Context().Err() if == context.DeadlineExceeded { serveError(, http.StatusRequestTimeout, .Error()) } else { // TODO: what's a good status code for canceled requests? 400? serveError(, http.StatusInternalServerError, .Error()) } return case <-.C: } , := collectProfile() if != nil { serveError(, http.StatusInternalServerError, "failed to collect profile") return } := .TimeNanos := .TimeNanos - .TimeNanos .Scale(-1) , = profile.Merge([]*profile.Profile{, }) if != nil { serveError(, http.StatusInternalServerError, "failed to compute delta") return } .TimeNanos = // set since we don't know what profile.Merge set for TimeNanos. .DurationNanos = .Header().Set("Content-Type", "application/octet-stream") .Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s-delta"`, )) .Write() } func collectProfile( *pprof.Profile) (*profile.Profile, error) { var bytes.Buffer if := .WriteTo(&, 0); != nil { return nil, } := time.Now().UnixNano() , := profile.Parse(&) if != nil { return nil, } .TimeNanos = return , nil } var profileSupportsDelta = map[handler]bool{ "allocs": true, "block": true, "goroutine": true, "heap": true, "mutex": true, "threadcreate": true, } var profileDescriptions = map[string]string{ "allocs": "A sampling of all past memory allocations", "block": "Stack traces that led to blocking on synchronization primitives", "cmdline": "The command line invocation of the current program", "goroutine": "Stack traces of all current goroutines. Use debug=2 as a query parameter to export in the same format as an unrecovered panic.", "heap": "A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample.", "mutex": "Stack traces of holders of contended mutexes", "profile": "CPU profile. You can specify the duration in the seconds GET parameter. After you get the profile file, use the go tool pprof command to investigate the profile.", "threadcreate": "Stack traces that led to the creation of new OS threads", "trace": "A trace of execution of the current program. You can specify the duration in the seconds GET parameter. After you get the trace file, use the go tool trace command to investigate the trace.", } type profileEntry struct { Name string Href string Desc string Count int } // Index responds with the pprof-formatted profile named by the request. // For example, "/debug/pprof/heap" serves the "heap" profile. // Index responds to a request for "/debug/pprof/" with an HTML page // listing the available profiles. func ( http.ResponseWriter, *http.Request) { if , := strings.CutPrefix(.URL.Path, "/debug/pprof/"); { if != "" { handler().ServeHTTP(, ) return } } .Header().Set("X-Content-Type-Options", "nosniff") .Header().Set("Content-Type", "text/html; charset=utf-8") var []profileEntry for , := range pprof.Profiles() { = append(, profileEntry{ Name: .Name(), Href: .Name(), Desc: profileDescriptions[.Name()], Count: .Count(), }) } // Adding other profiles exposed from within this package for , := range []string{"cmdline", "profile", "trace"} { = append(, profileEntry{ Name: , Href: , Desc: profileDescriptions[], }) } sort.Slice(, func(, int) bool { return [].Name < [].Name }) if := indexTmplExecute(, ); != nil { log.Print() } } func indexTmplExecute( io.Writer, []profileEntry) error { var bytes.Buffer .WriteString(`<html> <head> <title>/debug/pprof/</title> <style> .profile-name{ display:inline-block; width:6rem; } </style> </head> <body> /debug/pprof/ <br> <p>Set debug=1 as a query parameter to export in legacy text format</p> <br> Types of profiles available: <table> <thead><td>Count</td><td>Profile</td></thead> `) for , := range { := &url.URL{Path: .Href, RawQuery: "debug=1"} fmt.Fprintf(&, "<tr><td>%d</td><td><a href='%s'>%s</a></td></tr>\n", .Count, , html.EscapeString(.Name)) } .WriteString(`</table> <a href="goroutine?debug=2">full goroutine stack dump</a> <br> <p> Profile Descriptions: <ul> `) for , := range { fmt.Fprintf(&, "<li><div class=profile-name>%s: </div> %s</li>\n", html.EscapeString(.Name), html.EscapeString(.Desc)) } .WriteString(`</ul> </p> </body> </html>`) , := .Write(.Bytes()) return }