Skip to content

Go语言环境配置

📅 2026-07-05  |  📂 Go语言学习


在VSCode中配置Go语言开发环境

基本流程

  1. 配置基础环境
  2. 配置VSCode环境
  3. 安装生态工具

Go语言基础环境准备

首先,需要通过Go官方安装Go语言基础环境。安装之后,通过go version检查是否安装成功。

配置VSCode环境

安装Go扩展

安装Google官方开发的Go插件。

配置VSCode设置

json
{
  // 启用 Go 语言服务器(gopls),提供代码补全、跳转等核心功能
  "go.useLanguageServer": true,
 
  // 保存时自动格式化代码(搭配 goimports 效果更佳)
  "editor.formatOnSave": true,
 
  // 自动导入缺失的包,移除未使用的包(需安装 goimports)
  "go.importsOnSave": true,
 
  // 配置代码格式化工具(推荐 goimports,比 gofmt 多了 import 管理)
  "go.formatTool": "goimports",
 
  // 启用代码提示时的占位符(如函数参数提示)
  "gopls": {
    "usePlaceholders": true,
    "completeUnimported": true // 提示未导入的包
  }
}

安装Go生态工具

通过go install安装Go生态开发工具。

  1. 语言服务与代码补全工具:gopls
shell
go install golang.org/x/tools/gopls@latest
  1. 代码导航工具:go-outline
shell
go install github.com/ramya-rao-a/go-outline@latest
  1. 代码跳转工具:godef
shell
go install github.com/rogpeppe/godef@latest
  1. 代码格式化与导入管理工具:goimports、gofumpt
shell
go install golang.org/x/tools/cmd/goimports@latest
go install mvdan.cc/gofumpt@latest
  1. 静态代码检查工具:staticcheck、golangci-lint
shell
go install honnef.co/go/tools/cmd/staticcheck@latest
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
  1. 调试工具:delve
shell
go install github.com/go-delve/delve/cmd/dlv@latest
  1. 测试与覆盖率工具:gotests、gocov
shell
go install github.com/cweill/gotests/gotests@latest
go install github.com/axw/gocov/gocov@latest
  1. 代码生成工具:stringer、mockery
shell
go install golang.org/x/tools/cmd/stringer@latest
go install github.com/vektra/mockery/v2@latest

安装上述所有工具

shell
go install golang.org/x/tools/gopls@latest
go install github.com/ramya-rao-a/go-outline@latest
go install github.com/rogpeppe/godef@latest
go install golang.org/x/tools/cmd/goimports@latest
go install mvdan.cc/gofumpt@latest
go install honnef.co/go/tools/cmd/staticcheck@latest
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
go install github.com/go-delve/delve/cmd/dlv@latest
go install github.com/cweill/gotests/gotests@latest
go install github.com/axw/gocov/gocov@latest
go install golang.org/x/tools/cmd/stringer@latest
go install github.com/vektra/mockery/v2@latest

问题记录

安装工具gopls报错

报错信息

txt
go: golang.org/x/tools/gopls@latest: module golang.org/x/tools/gopls: Get "https://proxy.golang.org/golang.org/x/tools/gopls/@v/list": dial tcp [2607:f8b0:400a:809::2011]:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

问题分析

网络连接超时,导致下载失败。

问题解决

使用国内的Go社区代理服务

shell
go env -w GOPROXY=https://goproxy.cn,direct
  • -w参数会将设置永久写入Go环境配置,以后都不用再设置了;
  • ,direct表示如果代理找不到,则直接去源站拉取,作为兜底方案。

参考资料

Powered by VitePress