Package pkgload
is a set of utilities for go/packages
load-related operations.
Go version 1.17+
go get github.com/go-toolsmith/pkgload
package main
import (
"fmt"
"go/token"
"github.com/go-toolsmith/pkgload"
"golang.org/x/tools/go/packages"
)
func main() {
fset := token.NewFileSet()
cfg := &packages.Config{
Mode: packages.LoadSyntax,
Tests: true,
Fset: fset,
}
patterns := []string{"mypackage"}
pkgs, err := pkgload.LoadPackages(cfg, patterns)
if err != nil {
panic(err)
}
pkgs = pkgload.Deduplicate(pkgs)
pkgload.VisitUnits(pkgs, func(u *pkgload.Unit) {
pkgPath := u.NonNil().PkgPath
println(pkgPath)
})
}