Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use go importer

Tags:

go

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?

like image 573
Yifan Sun Avatar asked May 22 '19 14:05

Yifan Sun


People also ask

Is Gopath still needed?

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.

Can you import Main in go?

You cannot import the main package. Any shared code should go in a separate package, which can be imported by main (and other packages).


1 Answers

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
like image 130
Márcio Rocha Zacarias Avatar answered Oct 07 '22 17:10

Márcio Rocha Zacarias