分享
  1. 首页
  2. 文章

pprof接口隐藏/认证

写个代码容易么 · · 1559 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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界面了


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:写个代码容易么

查看原文:pprof接口隐藏/认证

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
1559 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏