go - How to find a package name from given call in runtime? -


for logging purpose want write function print package name. can directory name:

// file full file name // 4 - how many calls want go in stack trace. _, file, line, ok := runtime.caller(4)  

... can't find way package name (package name can different directory name).

i came across similar problem - package path how package name. best solution found exec "go list" command. not ideal came blank elsewhere.

in case had problem package empty directory. no source files, "go list" throws error, added function create sensible package name path.

here's code:

func getpackagename(path string) string {     output, err := exec.command("go", "list", "-f", "{{.name}}", path).combinedoutput()     if err != nil {         return guesspackagename(path)     }     return strings.trimspace(string(output)) }  func guesspackagename(path string) string {     preferred := path     if strings.hassuffix(preferred, "/") {         // training slashes tolerated, can rid of 1 if exists         preferred = preferred[:len(preferred)-1]     }     if strings.contains(preferred, "/") {         // if path contains "/", use last part         preferred = preferred[strings.lastindex(preferred, "/")+1:]     }     if strings.contains(preferred, "-") {         // name follows hyphen - e.g. github.com/foo/go-bar         // if package name contains "-", use last part         preferred = preferred[strings.lastindex(preferred, "-")+1:]     }     if strings.contains(preferred, ".") {         // dot commonly used version - e.g. github.com/foo/bar.v1         // if package name contains ".", use first part         preferred = preferred[:strings.lastindex(preferred, ".")]     }     return preferred } 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -