Home  >  Article  >  Backend Development  >  How to import local packages in go?

How to import local packages in go?

WBOY
WBOYforward
2024-02-11 14:27:08908browse

How to import local packages in go?

In the Go language, you can import local packages by using relative or absolute paths. First, make sure that your local package has a directory structure organized according to the Go language specifications. Then, in your Go file, use the import keyword to import the path to the package. When importing local packages, you can use relative or absolute paths. If your packages are in the same directory, you can use relative paths to import them, such as import "./utils". If your package is in a different directory, you can use an absolute path to import it, such as import "github.com/username/package/utils". In this way, you can successfully import the local package and use its functions and variables.

Question content

I'm new here and working on a sample code that I want to localize.

In the original main.go import statement it is:

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

Now I have common and routers packages 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 the following error:

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 solve this problem?

Solution

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

So I only need to add myapp in front of the package name, that is, the import should be:

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

The above is the detailed content of How to import local packages in go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete