How to solve the import-local-package problem: GOPATH is ignored, only GOROOT takes effects

1.9k Views Asked by At

I'm new in GO and has got stuck in environment configuration for hours.

I succeeded to run some test projects, but when I tried to import my custom local packages (say xxx), the "go run" command failed, logging that:

*test/main/main.go:6:2: package test/xxx is not in GOROOT (/usr/local/go/src/test/xxx)*

It is strange that GOPATH seems to be ignored when importing local packages on my ubuntu computer.

go version is go1.16.5 linux/amd64

GOPATH is set using export GOPATH="$HOME/GoProjects"

GOROOT is set using export GOPATH="/usr/local/go"

GoMod is "on" using go env -w GO111MODULE=on

After editing project's .go files, command "go mod init" and "go mod tidy" are typed in the root folder of the project ($GOPATH/src/test), and the project file structure looks like:

/src
  /.vscode
    -launch.json
  /gitbub.com
  /test
    /main
      -main.go     (here: import "test/xxx")
    /xxx
      -xxx.go      (here: package xxx)
    -go.mod        (almost empty - line 1: module test
                                   line 2: 
                                   line 3: go 1.16     )

What should I do to fix this problem?

2

There are 2 best solutions below

0
Zombo On BEST ANSWER

First, stop worrying about GOPATH. That is old stuff, and you don't need to do it any more. Then, make a folder somewhere test (doesn't need to be anything to do with GOPATH, just put in current directory, or wherever you want). Then make test/xxx. Then make test/xxx/xxx.go:

package xxx

const X = 1

Then make folder test/main. Then make test/main/main.go:

package main
import "test/xxx"

func main() {
   println(xxx.X)
}

Then go back to test, and do go mod init test. Then go back to test/main, and do go build. Done.

0
blami On

Assuming (not clear from your post) this entire tree is under your $HOME/GoProjects. When using modules; don't put your project inside GOPATH as mixing both GOPATH and modules only leads to problems.

First, set $GOPATH to something like $HOME/go which you can use to go get various tools you want to use across projects (such as e.g. dlv debugger and so on) but do not put your projects in there.

When starting a new project put it outside $GOPATH to $HOME/GoProjects/test (you can retain project layout you have under src but you do not need src there):

GoProjects
  /test
    /main
      -main.go
    /xxx
      -xxx.go

In project directory (here test) run go mod init NAME where NAME is name of your module. Do not use just test but fully qualified name which will namespace your project to your "domain" (e.g. github.com/yourusername/test). That name will then be used when importing packages from your module. So in main.go you will import xxx package (needs to have package xxx) like this:

import "github.com/yourusername/test/xxx"

See more info about modules here: https://blog.golang.org/using-go-modules