golang: 获取系统和应用的相关信息
一,代码:
1,controller/ImageController.go
//得到详情
func (ic *ImageController) Detail(c *gin.Context) {
// gin版本
ginVersion:=gin.Version
// golang 版本
golangVersion:=runtime.Version()
// 操作系统环境
os:=runtime.GOOS
//arch
arch:=runtime.GOARCH
//协程的数量
goroutineNum:=runtime.NumGoroutine()
//进程 id
pid:=syscall.Getpid()
//得到协程id
goroutineId := global.GetGoroutineId()
//得到用户
currentUser, err := user.Current()
if err != nil {
fmt.Println("无法获取当前用户信息:", err)
}
_, filename, line, _ := runtime.Caller(0)
vcs:=global.GetVcs()
c.JSON(http.StatusOK, gin.H{
"go_version":golangVersion, //go版本
"gin_version":ginVersion, //gin版本
"os":os, //操作系统
"arch":arch, //架构
"goroutine_num":goroutineNum, //当前协程数量
"process_id":pid, //当前进程id
"goroutine_id":goroutineId, //当前协程id
"current_userId":currentUser.Uid, //当前用户id
"current_userName":currentUser.Username, //当前用户名
"start_time":global.AppStartTime.Format("2006-01-02 15:04:05"), //进程启动时间
"current_file":filename, //当前代码文件
"current_line":line, //当前代码所在行
"vcs_revision":vcs["revision"], //git的commit
"vcs_time":vcs["time"], //git的commit的时间
"vcs_modified":vcs["modified"], //git此commit后是否又做了修改代码未提交
})
return
}
2, 用到的函数
//得到git的相关信息
func GetVcs() map[string]string {
vcs := map[string]string{
"revision": "",
"time": "",
"modified": "",
}
bi, ok := debug.ReadBuildInfo()
if !ok {
fmt.Println("Build info not available")
return vcs
} else {
for _, kv := range bi.Settings {
switch kv.Key {
case "vcs.revision":
Revision := kv.Value
vcs["revision"] = Revision
case "vcs.time":
buildTime, _ := time.ParseInLocation(time.RFC3339, kv.Value,time.Local)
timeLocal := buildTime.In(time.Local)
vcs["time"] = timeLocal.Format("2006-01-02 15:04:05")
case "vcs.modified":
DirtyBuild := kv.Value == "true"
vcs["modified"] = fmt.Sprintf("%t", DirtyBuild)
}
}
return vcs
}
}
//得到协程id
func GetGoroutineId() int {
buf := make([]byte, 32)
n := runtime.Stack(buf, false)
idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
id, err := strconv.Atoi(idField)
if err != nil {
return -1
}
return id
}
二,测试效果

浙公网安备 33010602011771号