Sobes.tech
Middle

How to embed the standard profiler into your Go application?

sobes.tech AI

Answer from AI

The net/http/pprof package provides HTTP handlers for profiling data.

Import it:

import (
	"net/http"
	_ "net/http/pprof" // Import for side effects
)

Run the HTTP server in a separate goroutine:

go func() {
	// Start server on localhost and default pprof port
	if err := http.ListenAndServe("localhost:6060", nil); err != nil {
		// Handle server start error, e.g., log it
		// log.Printf("pprof server failed: %v", err)
	}
}()

Now you can access profiling data at http://localhost:6060/debug/pprof/.

Main available endpoints:

  • /debug/pprof/: Main page with list of available profiles.
  • /debug/pprof/heap: Heap profile.
  • /debug/pprof/goroutine: Active goroutines profile.
  • /debug/pprof/block: Block profile.
  • /debug/pprof/threadcreate: OS thread creation profile.
  • /debug/pprof/cmdline: Application command line.
  • /debug/pprof/profile: CPU profile (collects data for 30 seconds by default).
  • /debug/pprof/trace: Execution trace profile (collects data for 1 second by default).

For analyzing CPU, heap, and block profiles, the go tool pprof utility is usually used:

go tool pprof http://localhost:6060/debug/pprof/profile # CPU profile for 30 seconds
go tool pprof http://localhost:6060/debug/pprof/heap # Heap profile

For execution trace analysis, the go tool trace utility is used:

go tool trace http://localhost:6060/debug/pprof/trace

Important: Remember about security and do not expose the pprof port externally without authentication in production.