Skip to content

Instantly share code, notes, and snippets.

@kjk kjk/show_caller_name.go
Last active Dec 31, 2015

Embed
What would you like to do?
Shows that we can get the caller's function name without access to source code. go build -o test show_caller_name.go; rm show_caller_name.go; ./test
package main
import (
"bytes"
"fmt"
"runtime"
)
var (
dunno = []byte("???")
centerDot = []byte("·")
dot = []byte(".")
)
func function(pc uintptr) []byte {
fn := runtime.FuncForPC(pc)
if fn == nil {
return dunno
}
name := []byte(fn.Name())
// The name includes the path name to the package, which is unnecessary
// since the file name is already included. Plus, it has center dots.
// That is, we see
// runtime/debug.*T·ptrmethod
// and want
// *T.ptrmethod
if period := bytes.Index(name, dot); period >= 0 {
name = name[period+1:]
}
name = bytes.Replace(name, centerDot, dot, -1)
return name
}
func showCallerName() {
pc, _, _, ok := runtime.Caller(1)
if !ok {
fmt.Printf("runtime.Caller() failed\n")
return
}
name := function(pc)
fmt.Printf("Caller name: %s\n", name)
}
func myCaller() {
showCallerName()
}
func main() {
myCaller()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.