Skip to content

Instantly share code, notes, and snippets.

@changkun
Created February 24, 2020 09:33
Show Gist options
  • Save changkun/161979dfedc0cd7d65dd06fe83b73cdc to your computer and use it in GitHub Desktop.
Save changkun/161979dfedc0cd7d65dd06fe83b73cdc to your computer and use it in GitHub Desktop.
get caller
func getFrame(skipFrames int) runtime.Frame {
// We need the frame at index skipFrames+2, since we never want runtime.Callers and getFrame
targetFrameIndex := skipFrames + 2
// Set size to targetFrameIndex+2 to ensure we have room for one more caller than we need
programCounters := make([]uintptr, targetFrameIndex+2)
n := runtime.Callers(0, programCounters)
frame := runtime.Frame{Function: "unknown"}
if n > 0 {
frames := runtime.CallersFrames(programCounters[:n])
for more, frameIndex := true, 0; more && frameIndex <= targetFrameIndex; frameIndex++ {
var frameCandidate runtime.Frame
frameCandidate, more = frames.Next()
if frameIndex == targetFrameIndex {
frame = frameCandidate
}
}
}
return frame
}
// MyCaller returns the caller of the function that called it :)
func MyCaller() string {
// Skip GetCallerFunctionName and the function to get the caller of
return getFrame(2).Function
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment