Last active
December 31, 2015 19:39
-
-
Save kjk/8034913 to your computer and use it in GitHub Desktop.
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
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 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