How to Debug Goroutine Leaks in Go

Debug goroutine leaks in Go by capturing a profile with runtime/pprof and analyzing the stack traces using go tool pprof.

Use runtime/pprof to capture a goroutine profile and inspect the stack traces to identify where goroutines are blocked or stuck. Run the following code snippet in your application to generate a profile file and then analyze it with go tool pprof.

import (
	"os"
	"runtime/pprof"
)

func main() {
	f, _ := os.Create("goroutine.prof")
	defer f.Close()
	pprof.Lookup("goroutine").WriteTo(f, 2)
	// Run your application logic here
}

After running the program, analyze the output with:

go tool pprof -top goroutine.prof

This displays the goroutines consuming the most resources and their call stacks, helping you pinpoint the leak source.