Go 模块在 VSCode 中导入问题(“无法在任何 [...] 中找到包 [...]”)

max*_*eth 21 go go-modules

我遇到了可能是 Gopls 语言服务器问题:在 VSCode 中使用带有 Go 扩展的 Go 模块时,我的所有外部包导入语句都被标记为不正确。这正是我到目前为止所做的:

在我的 GOPATH/src/github.com/Kozie1337/projectname 中:

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

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
}

[...]
Run Code Online (Sandbox Code Playgroud)

将鼠标悬停在github.com/gorilla/mux导入语句上时,出现错误:

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))"
Run Code Online (Sandbox Code Playgroud)

看起来它正在以没有 Go 模块的方式导入包,go\src即使它们go\pkg\mod现在存储在其中。VSCode/Gopls 是否有一些与此相关的配置文件,或者我做错了什么?我以前从未使用过 Go/Go 模块。

尽管存在 linting 错误,导入和代码实际上仍然有效,但该错误会禁用所有自动完成功能,因此仅忽略它并不是一个可行的解决方案。

我重新安装了 VSCode 的 Go 扩展并尝试重新启动语言服务器,但这没有改变任何东西。该错误消息出现在每个目录中的所有外部包导入语句中。

我很乐意提供一些建议。

小智 10

如果 Go 项目位于主项目目录的子目录中,则会出现相同的错误。要解决此问题,请在工作区根目录中打开 Go 项目,或将项目添加到 VScode 中的工作区。请参阅了解更多信息。


小智 7

我意识到这是一个老问题,但从 go 1.18 和 gopls@0.8.0 开始,他们引入了一种原生方法来支持此问题,即使用 go 工作区。

就我而言,我的 make 文件、docker-compose 文件等位于根目录中,所有项目位于 ./services 文件夹下,所以我这样做了:

root-dir> go work init
root-dir> go work use ./services/service1 ./services/service2
Run Code Online (Sandbox Code Playgroud)

这会将 go.work 文件添加到 root-dir 中,并且我不再出现上述错误。

在这里阅读更多内容:https ://github.com/golang/tools/blob/master/gopls/doc/workspace.md


Aru*_*ath 6

官方 go 模块博客文章特别提到“ $GOPATH/src之外的某个地方”。

所以在 GOPATH 之外初始化你的 go 模块。