Coyote
Coyote

Reputation: 2524

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

Upvotes: 0

Views: 475

Answers (1)

Thundercat
Thundercat

Reputation: 120931

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.

Upvotes: 1

Related Questions