Search code examples
gogo-modules

Go Modules importing issue in VSCode ("cannot find package [...] in any of [...]")


I'm encountering what probably seems to be a Gopls language server issue: All my external package import statements are being marked as incorrect when using Go Modules with the Go extension in VSCode. Here's exactly what I did so far:

Inside my GOPATH/src/github.com/Kozie1337/projectname:

  • run go mod init github.com/Kozie1337/projectname
  • run go get -u github.com/gorilla/mux

Inside go.main:

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/mux"  // This is being marked as wrong with the err. msg. down below
)

func main() {
  r := mux.NewRouter() // This actually works, even though the go linter says that mux isn't imported
  http.ListenAndServe(":9000", r)) // server starts too with mux routes
}

[...]

When hovering over the github.com/gorilla/mux import statement, I'm getting the error:

could not import github.com/gorilla/mux (cannot find package "github.com/gorilla/mux" in any of 
    C:\Program Files\Go\src\github.com\gorilla\mux (from $GOROOT)
    C\src\github.com\gorilla\mux (from $GOPATH)
    \Users\max\go\src\github.com\gorilla\mux (from $GOPATH))"

It looks like it's looking for the packages the way they were imported without Go modules from go\src even though they are stored in go\pkg\mod now. Is there some config file for VSCode/Gopls regarding this, or am I doing something wrong? I've never used Go/Go Modules before.

The import and code actually works despite the linting error, but the error disables all autocompletion so just ignoring it is not a viable solution.

I reinstalled to Go extension for VSCode and tried restarting the language server but that didn't change anything. The error message appears at all external package import statements, in every directory.

I'd be glad for some advice.


Solution

  • The official go modules blog post specifically says "somewhere outside $GOPATH/src,".

    So initialize you go module outside GOPATH.