0

Currently I have a parameter like str := "github.com/pkg/errors". I need the full path to the package.

Currently how I achieve this is by using build.Default.GOPATH+"/src/"+str.

Is there a native non hacky way of resolving the full path to an import (which could be in a vendor folder etc...).

Coyote
  • 2,454
  • 26
  • 47

1 Answers1

1

Use the go/build package to resolve an import path to a directory:

 p, err := build.Default.Import("github.com/pkg/errors", ".", build.FindOnly)
 if err != nil {
     // handle error
 }
 d := p.Dir

This snippet resolves local imports relative to the current working directory. Replace "." with "" if you don't want to resolve local imports or supply a different directory if appropriate.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242