pprof是golang提供的性能分析工具,这里就不过多介绍了。
使用方式很简单,导入pprof包即可
import _ "net/http/pprof"
pprof.go源文件init函数会初始化性能监控接口
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)
}
但是这种简单的方式使用会导致一个大问题,就是/debug/pprof接口会随着我们的应用暴露到公网
1. net/http
可通过http多路复用将pprof接口和业务接口隔离
业务接口使用8080端口,pprof接口使用内网的8081端口
package main
import (
"fmt"
"log"
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
//内网可访问的pprof地址
log.Fatal(http.ListenAndServe("127.0.0.1:8081", nil))
}()
mux := http.NewServeMux()
mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintf(writer, "hello")
})
//外网可访问的接口地址
log.Fatal(http.ListenAndServe(":8080", mux))
}
2. gin
如果使用gin框架,可通过gin-contrib/pprof包实现隔离/认证
import "github.com/gin-contrib/pprof"
package main
import (
"encoding/base64"
"fmt"
"github.com/gin-contrib/pprof"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
//自定义路由
//pprof.Register(router,"dev/pprof")
//注册默认路由 /debug/pprof
//pprof.Register(router)
//注册组,需要认证
authStr := fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte("admin:123456")))
pprofGroup := router.Group("/admin", func(c *gin.Context) {
auth := c.Request.Header.Get("Authorization")
if auth != authStr {
c.Header("www-Authenticate", "Basic")
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Next()
})
pprof.RouteRegister(pprofGroup, "pprof")
router.Run(":8080")
}
将pprof接口注册到admin路由组,如果账号密码错误响应头设置www-Authenticate: Basic,表示使用http基本认证(弹出登录框),并返回状态码401(未授权)
http基本认证会将(账号+冒号+密码)Base64后并添加Basic标识
如账号密码为admin/123456
base64(admin:123456) = YWRtaW46MTIzNDU2
最后请求头会添加
Authorization: Basic YWRtaW46MTIzNDU2
访问http://localhost:8080/admin/pprof/
后会弹出登录框,输入账号密码 admin/123456后就能访问pprof界面了
网友评论