I have been trying to use the importer to parse the types defined in a particular package. However, the importer always return an error saying the package is not found. What mistake I am making?
package main
import (
"fmt"
"go/importer"
)
func main() {
pkg, err := importer.Default().Import("github.com/onsi/ginkgo")
if err != nil {
panic(err)
}
fmt.Println(pkg)
}
I tried to read the go importer documentation, but it provides very limited information. I also tried to use the package I am importing here, but it does not help. However, if I import a go standard package, such as “time”, I can currently import the package. Why is that?
Since 1.12 version Go modules is enabled by default and the GOPATH will be deprecated in 1.13 version. For those who are getting started with Go 1.12, the installation and set up goes will be as follows.
You cannot import the main package. Any shared code should go in a separate package, which can be imported by main (and other packages).
Go importer will not download the package for you. You can use dep or go modules to handle your dependencies, but an easy fix would be downloading the package directly to your gopath using go get:
go get -u github.com/onsi/ginkgo
After that, go importer will work and your code output should be:
package ginkgo ("github.com/onsi/ginkgo")
[EDIT] Using Go Modules:
There's a bunch of tutorials about that, but the quick and dirty way is, on your package directory:
$ GO111MODULE=on go mod init
$ GO111MODULE=on go mod tidy
That will check your project and download all packages. To install a specific package on your go.mod
, you can use:
$ go install github.com/onsi/ginkgo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With