Search code examples
gogopathgo-packages

Getting full path to a package source from the package import path


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...).


Solution

  • 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.