获取调用函数的名称和包

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?

The results are correct. You'll need to do some parsing to format the results the way you want them; for example, try splitting on dots after the last slash in the string:

pc, _, _, _ := runtime.Caller(1)
funcName := runtime.FuncForPC(pc).Name()
lastSlash := strings.LastIndexByte(funcName, '/')
if lastSlash < 0 {
    lastSlash = 0
}
lastDot := strings.LastIndexByte(funcName[lastSlash:], '.') + lastSlash

fmt.Printf("Package: %s
", funcName[:lastDot])
fmt.Printf("Func:   %s
", funcName[lastDot+1:])

Playground: https://play.golang.org/p/-Nbos0a1Ifp