Last active
April 11, 2024 19:14
-
-
Save dexterp/e89663135c25c125725438042192f361 to your computer and use it in GitHub Desktop.
GO Function to retrieve call information
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package call | |
import ( | |
"path" | |
"runtime" | |
"strings" | |
) | |
type Info struct { | |
Dir string | |
File string | |
Package string | |
Line int | |
Type string | |
Func string | |
Call string | |
} | |
func CallInfo(depth int) *Info { | |
depth += 1 | |
pc, file, line, _ := runtime.Caller(depth) | |
dir, fileName := path.Split(file) | |
call := runtime.FuncForPC(pc).Name() | |
items := strings.Split(call, "/") | |
p := strings.Split(items[len(items)-1], ".") | |
var pkg, typ, fn string | |
switch len(p) { | |
case 3: // package, type, function | |
pkg = p[0] | |
typ = p[1] | |
fn = p[2] | |
case 2: | |
pkg = p[0] | |
fn = p[1] | |
} | |
return &Info{ | |
Dir: dir, | |
File: fileName, | |
Line: line, | |
Package: pkg, | |
Type: typ, | |
Func: fn, | |
Call: call, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment