how to import vscode path

Viewed 18175

I am receiving the following error from vscode when i try to edit a go file:

"Error loading workspace: You are outside of a module and outside of $GOPATH/src. If you are using modules, please open your editor to a directory in your module. If you believe this warning is incorrect, please file an issue: https://github.com/golang/go/issues/new."

My go path is set as follows: GOPATH=C:\Users\myusername\go

I have vscode and go working together just fine on other machines... but i cant figure out what is wrong here.

I am still new to go so i am a little confused as to what the point of the GOPATH is.

from the go docs its says: "The GOPATH environment variable specifies the location of your workspace"

and the for the definition of a workspace the docs say: "A workspace is a directory hierarchy with two directories at its root: "

so from what the docs are saying and what vscode is complaining about is that i have my code outside of the path "C:\Users\myusername\go"...

obviously go doesn't expect me to do all my work in the location "C:\Users\myusername\go" on my machine.

so what is it complaining about?

here is the output of my "gopls -rpc.trace -v check go_practice.go" command:

2021/04/21 16:05:23 Info:2021/04/21 16:05:23 go env for C:\projects\go_practice
(root C:\projects\go_practice)
(go version go version go1.16.3 windows/amd64)
(valid build configuration = false)
(build flags: [])
GOROOT=C:\Program Files\Go
GOSUMDB=sum.golang.org
GOFLAGS=
GOINSECURE=
GOPROXY=https://proxy.golang.org,direct
GO111MODULE=
GOCACHE=C:\Users\username\AppData\Local\go-build
GONOPROXY=
GOMOD=NUL
GOPRIVATE=
GOMODCACHE=C:\Users\username\go\pkg\mod
GONOSUMDB=
GOPATH=C:\Users\username\go
2 Answers

Maybe you have opened a directory with the following format in VSCode.

example dir
      |- project1
           |- main.go
           |- go.mod
           ...
      |- project2
           |- main.go
           |- go.mod
           ...
      |- project3
           |- main.go
           |- go.mod
           ...
...

Opening a directory containing multiple go.mod files will result in this error. The solution is to open only the project1 directory in VSCode, with only one go.mod file open.

You can initialize a so-called "go module" by running go mod init <name>, where name, usually, is your repository URL. (eg. github.com/user/repo)

This will generate a go.mod file. Read more about go modules here.

Related