Use the runtime/pprof package to capture CPU profiles and the net/http/pprof package to expose profiling endpoints on your HTTP server. Add the following code to your server initialization to enable profiling at /debug/pprof:
import (
"net/http"
"net/http/pprof"
)
func main() {
// Enable pprof endpoints
http.HandleFunc("/debug/pprof/", pprof.Index)
http.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
http.HandleFunc("/debug/pprof/profile", pprof.Profile)
http.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
http.HandleFunc("/debug/pprof/trace", pprof.Trace)
// Start your server
http.ListenAndServe(":8080", nil)
}
To capture a CPU profile for 30 seconds, visit http://localhost:8080/debug/pprof/profile?seconds=30 in your browser or use curl. Analyze the downloaded profile with go tool pprof <profile-file>.