Contents

golang pprof returns 404 page not found for debug/pprof

Contents

Hitting /debug/pprof/ always returned 404 page not found. The explanation starts with how net/http/pprof registers itself:

func init() {
	http.HandleFunc("/debug/pprof/", Index)
	http.HandleFunc("/debug/pprof/cmdline", Cmdline)
	http.HandleFunc("/debug/pprof/profile", Profile)
	http.HandleFunc("/debug/pprof/symbol", Symbol)
	http.HandleFunc("/debug/pprof/trace", Trace)
}

Importing _ "net/http/pprof" registers those five routes on http.DefaultServeMux from init. If the service uses its own router (httprouter, in my case), requests never reach DefaultServeMux, the pprof routes are dead weight, and you get a 404.

Knowing that, the first attempt was to register the same five routes on httprouter by hand. Sub-pages such as /debug/pprof/goroutine?debug=1 still returned 404 — httprouter matches /debug/pprof/ exactly and does not dispatch anything below it.

What actually works is mounting httprouter under the root path so DefaultServeMux keeps handling pprof:

http.Handle("/", router)
http.ListenAndServe(addr, nil)

Now both the router and pprof work.

Another option is a router with prefix matching, e.g. Gorilla:

router.NewRoute().PathPrefix("/debug/pprof/").HandlerFunc(pprof.Index)

I haven’t found an equivalent in httprouter — if you know of one, leave a comment.