Go语言源码阅读(6) – net/http/pprof | 性能剖析页面化
pprof.go
中的init初始化函数,使用 http.Handle
注册了一系列页面接口。
当在应用层的代码 import _ "net/http/pprof"
时,会执行init函数。即完整一些默认页面接口的注册。
如果你的程序没有开启http服务,那么还需要添加如下代码开启http服务:
import "net/http" http.ListenAndServe("0.0.0.0:10001", nil)
如果你的程序使用了router,而你就是执意想将profile信息通过router映射出来(比如你想复用router的监听地址),那么你可以手动在router中注册接口与 http/pprof
中的处理函数绑定。比如如下这样:
func AttachProfiler(router *mux.Router) { router.HandleFunc("/debug/pprof/", pprof.Index) router.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) router.HandleFunc("/debug/pprof/profile", pprof.Profile) router.HandleFunc("/debug/pprof/symbol", pprof.Symbol) // Manually add support for paths linked to by index page at /debug/pprof/ router.Handle("/debug/pprof/goroutine", pprof.Handler("goroutine")) router.Handle("/debug/pprof/heap", pprof.Handler("heap")) router.Handle("/debug/pprof/threadcreate", pprof.Handler("threadcreate")) router.Handle("/debug/pprof/block", pprof.Handler("block")) } // @NOTICE 拷贝自 https://stackoverflow.com/a/30201589
以下接口,会调用pprof包中的方法获取程序的profile信息并返回。
/debug/pprof/cmdline /debug/pprof/profile /debug/pprof/symbol /debug/pprof/trace
比如 /debug/pprof/profile
,在处理函数中会调用 pprof.StartCPUProfile
并sleep(默认30秒,可在调用接口时通过seconds参数指定),sleep接收后调用 pprof.StopCPUProfile
。
http.Handle("/debug/pprof/", http.HandlerFunc(Index))
这种写法,还会对 /debug/pprof/
的子uri进行处理,比如以下接口,都会进入到注册的 Index
处理函数。
/debug/pprof/goroutine /debug/pprof/heap /debug/pprof/threadcreate /debug/pprof/block
Index函数中会使用 /debug/pprof/
之后的字符串去pprof中查找是否存在对应的profile,如果存在,则调用对应的profile,如果不存在则直接返回 Unknown profile
给页面。
/debug/pprof
是导航页面。