1.2 常用工具
代码格式化
gofmt
Go 官方提供的格式化工具,所有 Go 代码都应该用 gofmt 格式化。
bash
# 格式化单个文件
gofmt main.go
# 格式化整个目录
gofmt -w .
# 查看差异而不修改
gofmt -d .
# 简化代码
gofmt -s -w .goimports
goimports 是 gofmt 的超集,额外自动添加/删除导入语句。
bash
# 安装
go install golang.org/x/tools/cmd/goimports@latest
# 使用
goimports -w .
# 格式化并本地化导入 (将长路径放在后面)
goimports -local example.com -w .格式化最佳实践
- 使用
go fmt或goimports作为唯一格式化工具 - 不要手动调整对齐和空格
- 在提交前自动格式化
代码检查
go vet
Go 内置的静态分析工具。
bash
# 检查常见错误
go vet ./...
# 检查特定分析器
go vet -printf ./... # 检查 printf 格式字符串
go vet -shadow ./... # 检查变量遮蔽
go vet -copylocks ./... # 检查锁复制
go vet -httpresponse ./... # 检查 HTTP 响应处理
go vet -nilness ./... # 检查 nil 指针staticcheck
更强大的静态分析工具。
bash
# 安装
go install honnef.co/go/tools/cmd/staticcheck@latest
# 运行
staticcheck ./...
# 查看详细信息
staticcheck -explain SA1000
# 忽略特定检查
staticcheck -checks=all,-ST1000 ./...常见检查项:
S: 代码简化建议SA: 静态分析错误ST: 样式问题Q: 代码质量问题
golangci-lint
集成了多个 linter 的快速检查工具。
bash
# 安装
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
# 运行 (默认启用多个 linter)
golangci-lint run
# 自动修复
golangci-lint run --fix
# 显示详细输出
golangci-lint run -v
# 生成不同格式报告
golangci-lint run --out-format=checkstyle > report.xml
golangci-lint run --out-format=json > report.json
# 只运行特定 linter
golangci-lint run --enable=gocyclo,misspell.golangci.yml 完整配置
yaml
# 输出配置
output:
formats:
- format: colored-line-number
print-issued-lines: true
print-linter-name: true
# 启用的 linter
linters:
enable:
# 默认启用的
- govet # 官方 vet 工具
- errcheck # 检查未处理的错误
- staticcheck # 静态检查
- unused # 未使用的代码
- gosimple # 简化建议
- ineffassign # 无效赋值
# 额外启用的
- gofmt # 格式检查
- goimports # 导入检查
- misspell # 拼写检查
- gocyclo # 循环复杂度
- dupl # 重复代码
- goconst # 常量提取
- unconvert # 不必要的转换
- prealloc # 预分配建议
- exportloopref # 循环变量引用检查
disable:
- depguard # 不启用依赖守卫
- lll # 不检查行长
# linter 配置
linters-settings:
gocyclo:
min-complexity: 15 # 循环复杂度阈值
dupl:
threshold: 100 # 重复代码阈值
goconst:
min-len: 2 # 最小字符串长度
min-occurrences: 2 # 最小出现次数
misspell:
locale: US # 拼写检查语言
goimports:
local-prefixes: example.com # 本地包前缀
# 运行配置
run:
timeout: 5m # 超时时间
tests: false # 是否检查测试文件
skip-dirs: # 跳过的目录
- vendor
- testdata
- mocks
skip-files: # 跳过的文件
- ".*\\.pb\\.go" # protobuf 生成的文件
- ".*_test\\.go" # 测试文件
# 问题过滤
issues:
exclude-rules:
- path: _test\.go
linters:
- gocyclo
- dupl
- gosec
exclude-use-default: false调试工具
Delve (dlv)
Go 的开源调试器。
bash
# 安装
go install github.com/go-delve/delve/cmd/dlv@latest基本调试命令
bash
# 调试程序
dlv debug main.go
# 带参数调试
dlv debug -- -arg1 value1
# 连接到运行中的进程
dlv attach <pid>
# 以服务器模式启动
dlv debug --headless --listen=:2345 --api-version=2Delve REPL 命令
(dlv) help # 显示帮助
(dlv) break main # 在 main 函数设置断点
(dlv) break main.go:10 # 在指定行设置断点
(dlv) break read.go:5 if x>0 # 条件断点
(dlv) continue # 继续执行
(dlv) next # 单步 (不进入函数)
(dlv) step # 单步 (进入函数)
(dlv) stepout # 执行完当前函数
(dlv) print variable # 打印变量值
(dlv) locals # 打印局部变量
(dlv) args # 打印参数
(dlv) set variable = value # 设置变量值
(dlv) goroutines # 查看所有 goroutine
(dlv) goroutine <id> # 切换到指定 goroutine
(dlv) stack # 查看调用栈
(dlv) frame <n> # 切换到指定栈帧
(dlv) list # 显示源代码
(dlv) whats-current # 显示当前位置
(dlv) quit # 退出调试VS Code 调试配置
json
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${fileDirname}",
"env": {
"DEBUG": "true"
},
"args": ["-config", "config.yaml"]
},
{
"name": "Launch File",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${file}",
"env": {},
"args": []
},
{
"name": "Attach to Process",
"type": "go",
"request": "attach",
"mode": "local",
"processId": 0,
"cwd": "${workspaceFolder}"
}
]
}调试技巧
go
// 1. 使用条件断点
// 在 VS Code 中断点右键 -> 编辑断点 -> 输入条件
// 例如:i == 10
// 2. 使用日志点 (不中断的断点)
// 在 VS Code 中断点右键 -> 编辑断点 -> 选择"日志消息"
// 输入:变量 x 的值为 {x}
// 3. 调试 goroutine
// (dlv) goroutines -group
// (dlv) goroutine <id> - 切换到指定 goroutine
// 4. 调试测试
dlv test ./package -run TestName
// 5. 核心文件调试
dlv core <executable> <corefile>性能分析工具
pprof
bash
# HTTP 端点 (在代码中导入)
import _ "net/http/pprof"
# 访问 http://localhost:6060/debug/pprof/
# CPU 分析
go tool pprof http://localhost:6060/debug/pprof/profile
# 内存分析
go tool pprof http://localhost:6060/debug/pprof/heap
# 阻塞分析
go tool pprof http://localhost:6060/debug/pprof/block
# 生成 SVG 火焰图
go tool pprof -svg ./app ./cpu.prof > cpu.svg
# 交互式分析
go tool pprof ./app ./cpu.prof
(pprof) top10 # 显示 top10 函数
(pprof) list FuncName # 显示函数源码
(pprof) web # 生成调用图trace 工具
bash
# 生成 trace 文件
go test -trace=trace.out ./...
# 或运行时生成
import "runtime/trace"
f, _ := os.Create("trace.out")
defer f.Close()
trace.Start(f)
defer trace.Stop()
# 查看 trace
go tool trace trace.out依赖管理工具
go mod 命令
bash
# 初始化模块
go mod init <module-name>
# 整理依赖
go mod tidy
# 下载依赖
go mod download
# 查看依赖树
go mod graph
# 查看为什么需要某个依赖
go mod why github.com/pkg/errors
# 验证依赖完整性
go mod verify
# 编辑 go.mod
go mod edit -replace github.com/pkg/errors=./local-errors
go mod edit -dropreplace github.com/pkg/errors
# 生成 vendor 目录
go mod vendorgo work (多模块工作区,Go 1.18+)
bash
# 初始化工作区
go work init
# 添加模块
go work use ./module1
go work use ./module2
# 查看工作区
go work listgovulncheck (安全漏洞检查)
bash
# 安装
go install golang.org/x/vuln/cmd/govulncheck@latest
# 检查当前模块
govulncheck ./...
# 检查指定包
govulncheck github.com/pkg/errors
# 检查 go.mod
govulncheck -mod=mod ./...文档工具
godoc
bash
# 安装
go install golang.org/x/tools/cmd/godoc@latest
# 启动文档服务器
godoc -http=:6060
# 访问 http://localhost:6060/pkg/your-modulego doc 命令
bash
# 查看包的文档
go doc fmt
# 查看函数的文档
go doc fmt.Println
# 查看完整文档
go doc -all fmt
# 查看源码
go doc -src fmt.Printlnswag (Swagger 文档生成)
bash
# 安装
go install github.com/swaggo/swag/cmd/swag@latest
# 生成文档
swag init -g cmd/main.go -o docs
# 生成并指定输出格式
swag init -g cmd/main.go --parseDependency --parseInternal --generatedTime测试工具
测试覆盖率
bash
# 生成覆盖率
go test -coverprofile=coverage.out ./...
# 查看覆盖率
go tool cover -func=coverage.out
# 生成 HTML 报告
go tool cover -html=coverage.out -o coverage.htmlgotestsum (改进的测试输出)
bash
# 安装
go install gotest.tools/gotestsum@latest
# 运行测试
gotestsum
# 生成 JUnit 报告
gotestsum --junitfile report.xml其他有用工具
air (热重载)
bash
# 安装
go install github.com/cosmtrek/air@latest
# 运行
air
# 初始化配置
air initgolangci-lint 预提交钩子
bash
# 安装 pre-commit
pip install pre-commit
# 添加钩子
pre-commit installmockgen (生成 mock)
bash
# 安装 (golang/mock 已归档,推荐使用 go.uber.org/mock)
go install go.uber.org/mock/mockgen@latest
# 生成 mock
mockgen -source=interface.go -destination=mocks/mock_interface.gostringer (生成 String 方法)
bash
# 安装
go install golang.org/x/tools/cmd/stringer@latest
# 生成
stringer -type=State工具安装脚本
bash
#!/bin/bash
# install-go-tools.sh
TOOLS=(
"github.com/golangci/golangci-lint/cmd/golangci-lint"
"github.com/go-delve/delve/cmd/dlv"
"golang.org/x/tools/cmd/goimports"
"golang.org/x/tools/cmd/stringer"
"github.com/golang/mock/mockgen"
"github.com/swaggo/swag/cmd/swag"
"golang.org/x/vuln/cmd/govulncheck"
"gotest.tools/gotestsum"
"github.com/cosmtrek/air"
)
for tool in "${TOOLS[@]}"; do
echo "Installing $tool..."
go install "$tool@latest"
done
echo "All tools installed!"工具链检查清单
开发前准备:
[ ] Go 已安装并配置好
[ ] GOPROXY 已配置 (国内用户)
[ ] IDE/编辑器已配置
[ ] goimports 已安装
[ ] golangci-lint 已安装
开发中:
[ ] 使用 gofmt/goimports 格式化代码
[ ] 使用 go vet 检查代码
[ ] 使用 golangci-lint 进行更全面检查
[ ] 编写测试并运行
调试时:
[ ] 使用 Delve 调试器
[ ] 使用 pprof 分析性能
[ ] 使用 trace 分析 goroutine
发布前:
[ ] 运行所有测试
[ ] 检查测试覆盖率
[ ] 运行 govulncheck
[ ] 生成文档