Getting function name with runtime and reflect

Hi,

The other two is fine but how do I get the actual name of main.main.func2?

Note: If I move Use function to main package, I’ll get what I want which is github.com/my/app/pkg/middleware.Timeout.func1 but I am not allowed to move it.

Thanks

Current result

github.com/my/app/pkg/middleware.RequestID
main.main.func2                               <--- This is no good!
github.com/my/app/pkg/middleware.Auth.RBAC-fm
package main

func main() {
	router.Use(middleware.RequestID)
	router.Use(middleware.Timeout(time.Second))

	auth := middleware.Auth{}
	router.Use(auth.RBAC)
}
package router

func Use(middleware func(http.Handler) http.Handler) {
	name := runtime.FuncForPC(reflect.ValueOf(middleware).Pointer()).Name()

	fmt.Println(name)
}
package middleware

func RequestID(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// ..

		next.ServeHTTP(w, r)
	})
}

type Auth struct{}

func (a Auth) RBAC(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// ...

		next.ServeHTTP(w, r)
	})
}

func Timeout(ttl time.Duration) func(handler http.Handler) http.Handler {
	return func(handler http.Handler) http.Handler {
		return http.TimeoutHandler(handler, ttl, " ")
	}
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.