笔者使用 macOS BigSur 安装完 Go 1.16.6 和 VSCode Go 插件,然后运行时,往往会报诸如下面的错误:

build esc: cannot load xxx : malformed module path “xxx”: missing dot in first path element

warning: GOPATH set to GOROOT (/Users/xxx/go/) has no effect

实际上,这都是由于 GOPATH 和 GOROOT 这两个关键参数配置错误造成的。至于这两个参数是什么含义,可以看我之前的博文:GOROOT、GOPATH 以及 Go 相关命令。

下面我将从 macOS 安装 go 开始来讲解配置流程:

  1. 首先,我们建立在使用 brew 安装 go 的前提下 brew install go
  2. 查看环境变量 在终端输入以下命令查看对应环境变量 go env GOPATH 查看 GOPATH go env GOROOT 查看 GOROOT 例如我的两个:
    1
    2
    3
    4
    $ go env GOPATH
    /Users/realyee/go
    $ go env GOROOT
    /usr/local/Cellar/go/1.16.6/libexec
  3. ~/.bash_profile或者~/.bashrc(如果你使用 zsh,则在~/.zshrc)中加入命令如下,下面的 GOPATH 和 GOROOT 都以我自己的为例,请对应修改
    1
    2
    3
    4
    export GOPATH=/Users/realyee/go
    export GOROOT=/usr/local/Cellar/go/1.16.6/libexec
    export PATH=$PATH:$GOPATH/bin
    export PATH=$PATH:$GOROOT/bin
  4. 在当前 shell 生效 source ~/.bash_profilesource ~/.zshrc

注意:在 macOS 上安装完 VSCode 之后,终端默认没有配置 code 命令,可以打开 Command Palette(Cmd+Shift+P),输入 shell command,将 code 命令安装到终端

配置 VSCode 设置

如果你用 VSCode 来进行 Go 编程,并且希望通过它进行 Debug 调试,安装如下插件: Go - Visual Studio Marketplace

打开 VSCode 的 setting.json(直接去目录找~/Library/Application Support/Code/User/settings.json也可)加入 go 相关配置:

注意

  1. 前两行中的 GOPATH 和 GOROOT 都以我自己的为例,请对应修改
  2. 注意修改第三行 HTTP 代理的端口,方便翻墙下载 go 工具
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"go.gopath": "/Users/realyee/go",
"go.goroot": "/usr/local/Cellar/go/1.16.6/libexec",
"http.proxy": "http://127.0.0.1:7890",
// Run Lint tool on save.
"go.lintOnSave": "file", //在保存代码时自动检查代码可以优化的地方,并给出建议
"go.formatTool": "gofmt", //使用 goimports 工具进行代码格式化,或者使用 goreturns 和 gofmt
"go.docsTool": "gogetdoc",
"go.autocompleteUnimportedPackages": true,
// Specifies Lint tool name.
"go.lintTool": "golint",
// Flags to pass to Lint tool (e.g. ["-min_confidence=.8"])
"go.lintFlags": [],
"go.coverOnSave": false, //在保存代码时执行测试,并显示测试覆盖率
"go.useCodeSnippetsOnFunctionSuggest": true, //使用代码片段作为提示
"go.gocodeAutoBuild": false, //代码自动编译构建
"cSpell.enableFiletypes": [
"go.mod",
"go.sum"
],
"[go]": {
"editor.insertSpaces": false,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
"editor.suggest.snippetsPreventQuickSuggestions": false
}

然后打开 Command Palette(Cmd+Shift+P),输入 go:install,点击选择 Go:Install/Update Tools,全选所有工具进行安装。最后在项目目录的 .vscode 目录的 launch.json 中添加如下:

1
2
3
4
5
6
7
8
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}",
"args":["serve"]
}

下面就可以在 Debug 页面找到 Launch Package 选项快乐地 debug go 了。

参考文章

  1. Running Visual Studio Code on macOS
  2. Visual Studio Code for mac 设置代理 安装 go 开发环境_mixboot-CSDN 博客