筆者使用 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 開始來講解配置流程:
- 首先,我們建立在使用 brew 安裝 go 的前提下
brew install go
- 查看環境變量
在終端輸入以下命令查看對應環境變量
go env GOPATH
查看 GOPATH
go env GOROOT
查看 GOROOT
例如我的兩個:$ go env GOPATH /Users/vio1etus/go $ go env GOROOT /usr/local/Cellar/go/1.16.6/libexec
- 在
~/.bash_profile
或者~/.bashrc
(如果你使用 zsh,則在~/.zshrc
)中加入命令如下,下面的 GOPATH 和 GOROOT 都以我自己的為例,請對應修改:export GOPATH=/Users/vio1etus/go export GOROOT=/usr/local/Cellar/go/1.16.6/libexec export PATH=$PATH:$GOPATH/bin export PATH=$PATH:$GOROOT/bin
- 在當前 shell 生效
source ~/.bash_profile
或source ~/.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 相關配置:
注意:
- 前兩行中的 GOPATH 和 GOROOT 都以我自己的為例,請對應修改
- 注意修改第三行 HTTP 代理的端口,方便FQ下載 go 工具
"go.gopath": "/Users/vio1etus/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 中添加如下:
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}",
"args":["serve"]
}
下面就可以在 Debug 頁面找到 Launch Package 選項快樂地 debug go 了。