vscode for go
常用快捷键
ctrl+space
:手动代码提示(Trigger Suggest)
ctrl+k ctrl+0
:折叠所有代码块(Fold ALL)
ctrl+k ctrl+j
:折叠所有代码块(Unfold ALL)
alt+left
=>ctrl+-
:回退到上一步(go back)
alt+right
=>ctrl++
:下一步(go forward)
ctrl+f
:在当前文件中查找(Find in file)
ctrl+h
:在当前文件中替换(Replace in file)
ctrl+shift+f
:在当前文件夹查找(Find in files)
ctrl+shift+h
:在当前文件夹替换(Replace in files)
none
:代码格式化(Format Document)
gopls
之前vscode for golang需要安装十几个命令行工具,在vscode 1.30.2版本(2018年)中,vscode加入了后台进程gopls来更好的支持代码提示、转到定义等功能。gopls for vscode
更多用法参见 github
gopls安装
以 ubuntu on windows 为例,安装 vs code with gopls。
下载最新版本golang,并配置好环境变量
cd; mkdir -p program golang curl -Lo go.tar.gz https://dl.google.com/go/go1.14.2.linux-amd64.tar.gz tar -zxf go.tar.gz -C program/ echo export GOROOT=$PWD/program/go >> .bashrc echo export GOPATH=$PWD/golang >> .bashrc echo 'PATH=$PATH:$GOROOT/bin:$GOPATH/bin' >> .bashrc . .bashrc
安装gopls
go get golang.org/x/tools/gopls@latest
启动vscode
code -n golang/myproject
常用配置
打开配置文件 File > Preferences > Settings > User > Open JSON
:
// 将设置放入此文件中以覆盖默认设置
{
"editor.minimap.enabled": true,
"editor.minimap.renderCharacters": false,
"window.zoomLevel": 0,
// go plugin Configuragion
// "go.buildOnSave": true,
"go.toolsEnvVars": {"GOOS" : "linux"},
"go.useCodeSnippetsOnFunctionSuggest": false,
// gopls Configuration
"go.useLanguageServer": true,
"[go]": {
"editor.formatOnSave": false,
"editor.codeActionsOnSave": {
"source.organizeImports": true,
},
// Optional: Disable snippets, as they conflict with completion ranking.
"editor.snippetSuggestions": "none",
},
"[go.mod]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true,
},
},
"gopls": {
// Add parameter placeholders when completing a function.
"usePlaceholders": true,
// If true, enable additional analyses with staticcheck.
// Warning: This will significantly increase memory usage.
"staticcheck": false,
},
// code-runner Configuration
"code-runner.runInTerminal": true,
"terminal.integrated.shell.linux": "/bin/bash"
}
依赖私有仓库
如果项目的go.mod
中依赖了私有仓库,则vscode会因为go get
私有仓库失败而导致加载项目失败,这时需要如下配置。
跳过对私有仓库的代理和校验:
go env -w GOPRIVATE="*.name.com,gitlab.com/xyz"
go get
私有仓库时使用ssh方式而非https方式,在~/.gitconfig
加入:
[url "git@gitlab.com:"]
insteadOf = https://gitlab.com/
加载项目
加载golang项目有两种情况:
- go mod项目:直接打开项目即可。
- go vendor项目:打开项目后,修改
Workspace
区配置并重启vscode:
"go.toolsEnvVars": {"GO111MODULE": "off"}
问题记录
当代码提示功能失效时,可能是mod中的包无法解析,包版本不能写v0.0.0,应该写latest,执行go mod tidy
即可。
当vscode自动编译项目时提示找不到某动态库,则可以在启动vscode时注入环境变量
GO111MODULE=on CGO_LDFLAGS="-L /Users/sycki/coding/src/qiaodata.com/sycki/slimming-service/lib/darwin-amd64" http_proxy=socks5://localhost:1080 https_proxy=socks5://localhost:1080 no_proxy=github.com,gopkg.in code src/qiaodata.com/sycki/slimming-service