Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import local packages in go?

Tags:

go

I am new to go and working on an example code that I want to localize.

In the original main.go import statement it was:

 import (
    "log"
    "net/http"
    "github.com/foo/bar/myapp/common"
    "github.com/foo/bar/myapp/routers"
)

Now I have common and routers package in /home/me/go/src/myapp

So I converted the import statement to:

import (
    "log"
    "net/http"
    "./common"
    "./routers"
)

But when I run go install myapp I get these errors:

can't load package: /home/me/go/src/myapp/main.go:7:3: local import "./common" in non-local package

Also, when I use common and routers instead of ./common and ./routers in the import statement, I get:

myapp/main.go:7:3: cannot find package "common" in any of:
    /usr/local/go/src/common (from $GOROOT)
    /home/me/go/src/common (from $GOPATH)
myapp/main.go:8:2: cannot find package "routers" in any of:
    /usr/local/go/src/routers (from $GOROOT)
    /home/me/go/src/routers (from $GOPATH)

How can I fix this?

like image 234
Karlom Avatar asked Oct 11 '22 21:10

Karlom


People also ask

How do I import go packages into a project?

When importing packages, the first step is to create a new module. For instance, under the workspace directory, we can build a new module as follows: The file provides the module name and the Go version because we don’t have any external packages. Build a new directory in your project and place the source code files beneath it to create a package.

How to import local package in Go language?

Basically Go starting path for import is $HOME/go/src So I just needed to add myapp in front of the package names, that is, the import should be: Show activity on this post. If you are using Go 1.5 above, you can try to use vendoring feature. It allows you to put your local package under vendor folder and import it with shorter path.

How to import local package in vendor folder in go?

If you are using Go 1.5 above, you can try to use vendoring feature. It allows you to put your local package under vendor folder and import it with shorter path. In your case, you can put your common and routers folder inside vendor folder so it would be like

How do I use functions in a package in go?

To make use of the functions in a package, you need to access the package with an import statement. An import statement is made up of the import keyword along with the name of the package. As an example, in the Go program file random.go you can import the math/rand package to generate random numbers in this manner:


1 Answers

Well, I figured out the problem. Basically Go starting path for import is $HOME/go/src

So I just needed to add myapp in front of the package names, that is, the import should be:

import (
    "log"
    "net/http"
    "myapp/common"
    "myapp/routers"
)
like image 121
Karlom Avatar answered Oct 13 '22 11:10

Karlom