Created
February 24, 2020 09:33
-
-
Save changkun/161979dfedc0cd7d65dd06fe83b73cdc to your computer and use it in GitHub Desktop.
get caller
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
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