package tool

import (
	"net/http"
	"net/http/pprof"

	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
)

// import "net/http/pprof"
// import "runtime/pprof"
// 其中 net/http/pprof 使用 runtime/pprof 包来进行封装，并在 http 端口上暴露出来。
// runtime/pprof 可以用来产生 dump 文件，再使用 Go Tool PProf 来分析这运行日志。

// 插入 pprof 由于用了*runtime.ServeMux 所以需要自己定义路由
func RegisterPprof(serviceMux *runtime.ServeMux) {
	serviceMux.HandlePath("GET", "/debug/pprof/{path}", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
		pprof.Index(w, r)
	})
	serviceMux.HandlePath("GET", "/debug/pprof/cmdline", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
		pprof.Cmdline(w, r)
	})
	serviceMux.HandlePath("GET", "/debug/pprof/profile", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
		pprof.Profile(w, r)
	})
	serviceMux.HandlePath("GET", "/debug/pprof/symbol", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
		pprof.Symbol(w, r)
	})
	serviceMux.HandlePath("GET", "/debug/pprof/trace", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
		pprof.Trace(w, r)
	})
}
