how to get function name?

3,073 views
Skip to first unread message

Johnson

unread,
Jan 9, 2012, 7:11:30 PM1/9/12
to golang-nuts
i'm trying to use the function name as a variable within the function.


something like:


func helloHandler(w http.ResponseWriter, r *http.Request) {
funcname := ??????
fmt.Fprintf(w, "the function name is %s", funcname)
}

any tips?

John Asmuth

unread,
Jan 9, 2012, 8:01:57 PM1/9/12
to golan...@googlegroups.com
It looks like "helloHandler", to me!

But you can use runtime.Caller() to finagle this information out of the sytem.

Glenn Brown

unread,
Jan 9, 2012, 8:09:16 PM1/9/12
to Johnson, golang-nuts

> i'm trying to use the function name as a variable within the function.

Caller() in pkg/runtime returns the Program Counter.
PCToFunc() in debug/gosym converts the PC to a function name.
(But I wonder if it works on strip'd binaries.)

--Glenn

Johnson

unread,
Jan 9, 2012, 8:27:31 PM1/9/12
to golang-nuts
I'm still having trouble, what am I doing wrong?

I was able to get the file name with the below: the function name is
code/hello.go

_, funcname, _, _ := runtime.Caller(0)
fmt.Fprintf(w, "the function name is %s", funcname)


trying to pass the PC to gosym.PCToFunc is throwing this error:

funcname, _, _, _ := runtime.Caller(0)
fmt.Fprintf(w, "the function name is %v", gosym.PCToFunc(funcname))

Kyle Lemons

unread,
Jan 9, 2012, 9:08:36 PM1/9/12
to Johnson, golang-nuts
Not sure why you need gosym...

Reply all
Reply to author
Forward
0 new messages