52 lines
2.4 KiB
Go
52 lines
2.4 KiB
Go
// Package pprof 将标准库分析 Handler 显式注册到框架服务器,不改变业务认证。
|
|
// 只有导入本子包才依赖 net/http/pprof,普通 http 包不会隐式加载分析 Handler。
|
|
package pprof
|
|
|
|
import (
|
|
"net"
|
|
"net/http"
|
|
native "net/http/pprof"
|
|
"strings"
|
|
|
|
framework "git.zhangdeman.cn/zhangdeman/ginframework/http"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// Register 原子注册 /debug/pprof 的标准库分析入口,应用须显式调用才会挂载 Gin 路由。
|
|
// 入参:server 为应用已创建的框架服务,authorize 为可选鉴权;nil 仅允许 TCP 回环对端。
|
|
// 返回:框架路由冲突或冻结错误;不会部分注册、不创建监听器或依赖 DefaultServeMux 提供服务。
|
|
// 隐式逻辑:鉴权回调替代默认回环限制,失败必须 Abort;转发头不参与默认对端判断。
|
|
func Register(server *framework.Server, authorize gin.HandlerFunc) error {
|
|
if authorize == nil {
|
|
authorize = loopbackOnly
|
|
}
|
|
routes := []framework.NativeRoute{}
|
|
for _, item := range []struct {
|
|
name string `dc:"标准库分析路由后缀"`
|
|
handler http.HandlerFunc `dc:"标准库分析请求处理器"`
|
|
}{
|
|
{"", native.Index}, {"cmdline", native.Cmdline}, {"profile", native.Profile}, {"symbol", native.Symbol}, {"trace", native.Trace},
|
|
} {
|
|
routes = append(routes, framework.NativeRoute{Metadata: framework.Metadata{Method: http.MethodGet, Path: "/debug/pprof/" + item.name}, Handlers: []gin.HandlerFunc{authorize, gin.WrapF(item.handler)}})
|
|
}
|
|
for _, name := range []string{"allocs", "block", "goroutine", "heap", "mutex", "threadcreate"} {
|
|
routes = append(routes, framework.NativeRoute{Metadata: framework.Metadata{Method: http.MethodGet, Path: "/debug/pprof/" + name}, Handlers: []gin.HandlerFunc{authorize, gin.WrapH(native.Handler(name))}})
|
|
}
|
|
routes = append(routes, framework.NativeRoute{Metadata: framework.Metadata{Method: http.MethodPost, Path: "/debug/pprof/symbol"}, Handlers: []gin.HandlerFunc{authorize, gin.WrapF(native.Symbol)}})
|
|
return server.HandleBatch(routes...)
|
|
}
|
|
|
|
// loopbackOnly 只信任 Request.RemoteAddr 的回环对端;入参为当前请求,拒绝时终止处理。
|
|
func loopbackOnly(ctx *gin.Context) {
|
|
host, _, err := net.SplitHostPort(strings.TrimSpace(ctx.Request.RemoteAddr))
|
|
if err != nil {
|
|
host = ctx.Request.RemoteAddr
|
|
}
|
|
ip := net.ParseIP(strings.Trim(host, "[]"))
|
|
if ip == nil || !ip.IsLoopback() {
|
|
ctx.AbortWithStatus(http.StatusForbidden)
|
|
return
|
|
}
|
|
ctx.Next()
|
|
}
|