Pprof HTTP Runtime Profiling Endpoint

Expose Go runtime profiling endpoints on an internal port, sampling CPU flame graphs, heap snapshots, and goroutine dumps.

GoCli Tooling

Code

gosnippet
53 lines
package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/pprof"
	"runtime"
	"time"
)

func busyWork() {
	total := 0
	for i := 0; i < 2_000_000; i++ {
		total += i % 7
	}
	_ = total
}

func setupProfiler(addr string) *http.Server {
	mux := http.NewServeMux()
	mux.HandleFunc("/debug/pprof/", pprof.Index)
	mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
	mux.HandleFunc("/debug/pprof/heap", pprof.Handler("heap").ServeHTTP)
	mux.HandleFunc("/debug/pprof/goroutine", pprof.Handler("goroutine").ServeHTTP)

	server := &http.Server{Addr: addr, Handler: mux}
	go func() {
		log.Printf("pprof listening on %s", addr)
		if err := server.ListenAndServe(); err != http.ErrServerClosed {
			log.Printf("pprof server error: %v", err)
		}
	}()
	return server
}

func main() {
	prof := setupProfiler("127.0.0.1:6060") // 仅内网可达,不暴露公网
	defer prof.Close()

	runtime.SetMutexProfileFraction(5)
	runtime.SetBlockProfileRate(200)

	for i := 0; i < 3; i++ {
		busyWork()
		time.Sleep(100 * time.Millisecond)
	}

	// 使用方式:
	// go tool pprof http://127.0.0.1:6060/debug/pprof/profile?seconds=10
	// go tool pprof http://127.0.0.1:6060/debug/pprof/heap
	fmt.Println("profile samples collected")
}

What the statements do

What another module actually calls is the functions busyWork, setupProfiler and main — everything else is wiring.

Repetition is confined to for i := 0; i < 2_000_000; i++ — the rest of the file is straight-line. A goroutine takes the work off the current one. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Putting it to use

The signature you will reach for first is func busyWork()

The demo output is labeled (profile samples collected), so every line in the printed output names the step that produced it.

Execute the file and main walks through setupProfiler and busyWork, in that order.

Core lines

func busyWork() {
	total := 0
	for i := 0; i < 2_000_000; i++ {
		total += i % 7
	}
	_ = total
}
defer prof.Close()

Interactive Tools for This Topic

FAQ

What does Pprof HTTP Runtime Profiling Endpoint print when run?
Run it as a complete program — the output lines carry labels such as `profile samples collected`.