Golang VSCode 開發環境建置
用了一陣子的 VSCode 作為 Golang 的 IDE ,使用上蠻順手的沒什麼特別雷的地方,因此記錄一下如何在 macOS 的 VScode 建置最基本的 Golang 開發環境。
本文環境
- macOS 10.16
Requirements
VSCode Extension - Go
安裝完 VSCode 與 Golang 之後,打開 VSCode 的擴充功能,安裝 Go (微軟官方維護) 擴充功能。
GOPATH 設定
GOPATH 是 Golang 很重要的一項環境變數,如果要查看現在的 GOPATH 設定,可以按下 Command + Shift + p
呼叫命令列視窗,輸入 Go: Current GOPATH
查看。
如果要設定 GOPATH 則可以按下 Command + ,
開啟使用者設定,輸入 "go.gopath": "<your gopath>"
進行設定。
安裝 Golang 相關工具
Go 擴充功能整合了多種 Go 工具,例如 gocode, gorename, godoc, golint 等,詳見 文件 ,這些工具預設會裝在 GOPATH
底下,裝完之後就擁有最基本的 Go 開發環境。
裝完擴充功能之後,在 VSCode 編輯個 .go
作為副檔名的檔案,可能會看到右下角出現 Analysis Tools Missing
,此時可以按下 Command + Shift + p
呼叫命令列視窗,輸入 Go: Install/Update tools
安裝/更新所有的工具解決此問題。
p.s. 如果未設定好 GOPATH 可能會出現 vscode go get golang.org/x/tools/gopls: mkdir /usr/local/go/bin/pkg: permission denied
等權限問題
Debug with VSCode
裝完 Go 擴充功能之後,此時 VSCode 也已經裝有 Golang Debug 的工具,可以寫一段程式後按下 F5
試試。
修改 Debug 工具設定的檔案是左側側邊欄的 launch.json
。預設的 launch.json
如下:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"port": 2345,
"host": "127.0.0.1",
"program": "${fileDirname}",
"env": {},
"args": [],
"showLog": true
}
]
}
如果是要在工作區內直接 Debug ,可以把 ${fileDirname}
換成 ${workspaceFolder}
。其他更詳細的設定可以參閱 Debugging-Go-code-using-VS-Code ,該文件也說明如何進行遠端偵錯(Remote Debugging)。
以上。 Happy Coding!
References
https://github.com/Microsoft/vscode-go/wiki/Go-tools-that-the-Go-extension-depends-on
https://github.com/Microsoft/vscode-go/wiki/GOPATH-in-the-VS-Code-Go-extension
https://github.com/Microsoft/vscode-go/wiki/Debugging-Go-code-using-VS-Code