Can't use go tool pprof with an existing server

[亡魂溺海] 提交于 2019-12-03 10:56:05

It's not explicitly mentioned in the documentation, but net/http/pprof only registers its handlers with http.DefaultServeMux.

From the source:

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

If you're not using the default mux you just have to register any/all of those you want with whatever mux you're using, e.g. something like mymux.HandleFunc("…", pprof.Index), etc.

Alternatively you can listen on a separate port (also possibly bound to only localhost if desired) with the default mux as you've shown.

Looks like the problem was in a *mux.Router used from github.com/gorilla/mux which I used as a Handler in my http.Server instance.

Solution: just launch one more server just for the pprof:

server := &http.Server {
    Addr:           ":8080",
    Handler:        router,
    ReadTimeout:    15*time.Second,
    WriteTimeout:   15*time.Second,
}
go func() {
    log.Println(http.ListenAndServe(":6060", nil))
}()
log.Fatal(server.ListenAndServe())
Devon Peticolas

If you're using a github.com/gorilla/mux.Router you can simply hand off any request prefixed with /debug/ to the http.DefaultServeMux.

import _ "net/http/debug"
router := mux.NewRouter()
router.PathPrefix("/debug/").Handler(http.DefaultServeMux)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!