Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

go-modules

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.

like image 677
maxeth Avatar asked Nov 16 '25 03:11

maxeth


1 Answers

Same error can come if the Go project is in a subdirectory of the main project directory. To solve this, either open the Go project in workspace root or add the project to workspace in VScode. See this for more info.

like image 57
Basil K Y Avatar answered Nov 18 '25 20:11

Basil K Y



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!