I need to know the name of the go-package and function (including the receiver name) of the calling function.
This is my current code:
func retrieveCallInfo() {
pc, _, _, _ := runtime.Caller(1)
funcName := runtime.FuncForPC(pc).Name()
lastDot := strings.LastIndexByte(funcName, '.')
fmt.Printf(" Package: %s
", funcName[:lastDot])
fmt.Printf(" Func: %s
", funcName[lastDot+1:])
}
However, the code doesn't behave exactly as it should.
// When called from a conventional (free) function:
runtime.FuncForPC(pc).Name() // returns <package-path>.<funcName>
// When called from a method receiver function:
runtime.FuncForPC(pc).Name() // returns <package-path>.<receiverName>.<funcName>
When called from a receiver function, the receiver name is part of the package name, rather than the function name - which is not what I want.
Here's a demonstration: https://play.golang.org/p/-99sZXr4ptD
In the second example, I want the package name to be main
and the function name to be empty.f
.
Since dots are also valid parts of a package name, I can't simply split at another dot - maybe it's actually not the receiver, but part of the package name.
Hence, the information returned by runtime.FuncForPC()
is ambiguous and not enough.
How can I get the correct results?