1 Star 5 Fork 0

A-涛/gotool

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
caller.go 1.94 KB
一键复制 编辑 原始数据 按行查看 历史
A-涛 提交于 2022-06-27 15:57 . update
package xdebug
import (
"runtime"
"strings"
)
const (
maxDepth = 1000
xDebugCaller = "/xdebug/caller.go"
)
// GetSysPathSplitSymbol 根据系统获取路径分隔符
func GetSysPathSplitSymbol() (splitSymbol string) {
if runtime.GOOS == "windows" {
splitSymbol = "\\"
} else {
splitSymbol = "/"
}
return
}
// ParseCallFile 解析调用文件
func ParseCallFile(filename string) string {
lastIndex := strings.LastIndex(filename, GetSysPathSplitSymbol())
if lastIndex == -1 {
return ""
}
return filename[lastIndex+1:]
}
// callerFromIndex 返回调用者的位置和信息
// 说明: 返回的索引值应该是 <index - 1> 作为调用者的起始点
func callerFromIndex(filters []string) (pc uintptr, file string, line int, index int) {
var filtered, ok bool
for index = 0; index < maxDepth; index++ {
pc, file, line, ok = runtime.Caller(index)
if !ok {
break
}
filtered = false
for _, filter := range filters {
if filter != "" && strings.Contains(file, filter) {
filtered = true
break
}
}
if filtered {
continue
}
if strings.HasSuffix(file, xDebugCaller) {
continue
}
return
}
return 0, "", -1, -1
}
// CallerPathWithFilter 返回函数名和绝对文件路径调用者的行号
// filter 用于过滤调用者的路径。
func CallerWithFilter(filter string, skip ...int) (function string, path string, line int) {
num := 0
if len(skip) > 0 {
num = skip[0]
}
var ok bool
pc, file, line, start := callerFromIndex([]string{filter})
if start != -1 {
for i := start + num; i < maxDepth; i++ {
if i != start {
pc, file, line, ok = runtime.Caller(i)
}
if ok {
if filter != "" && strings.Contains(file, filter) {
continue
}
function := ""
if fn := runtime.FuncForPC(pc); fn == nil {
function = "unknown"
} else {
function = fn.Name()
}
return function, file, line
} else {
break
}
}
return function, file, line
}
return "", "", -1
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/xuesongtao/gotool.git
git@gitee.com:xuesongtao/gotool.git
xuesongtao
gotool
gotool
v1.1.9

搜索帮助

0d507c66 1850385 C8b1a773 1850385