golang pprof访问debug/pprof报404 page not found的解决办法
目录
这个问题要从net/http/pprof的原理说起,可以看到
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) }
引入 _ “net/http/pprof”,init函数会添加pprof的路由信息,而如果http注册了其他路由,导致http.HandleFunc失效,也就会造成了404的问题,我使用的是httprouter包
知道这个原理,手动添加上面5条路由,再次尝试,访问http://localhost:8080/debug/pprof/goroutine?debug=1等其他内部页面时,仍旧报404,再次分析原因,httprouter添加路由信息,如第一条,仅添加了/debug/pprof/的路由信息,并不会对子路径作路由牵引,导致404
所以解决办法:
用http.Handle(“/”, router) 将httprouter的路由注册给http路由,http.ListenAndServe(addr, nil) 替代http.ListenAndServe(addr, router),这时,router和http/pprof都可以生效了
http.Handle("/", router) http.ListenAndServe(addr, nil)
当然还可以用第三方router的prefix功能,如Gorilla的
router.NewRoute().PathPrefix("/debug/pprof/").HandlerFunc(pprof.Index)
httprouter还未发现这样的功能,有了解的可以留言给我