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

snippet
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")
}