Go语言工程化
Edited
Package/Module/Dependency
- 安装模块
go get module
go get [email protected]
# 安装特定commit hash/branch
go get module@4cf76c2
go get module@bugfix- 引用本地模块
require example.com/theirmodule v0.0.0-unpublished
replace example.com/theirmodule v0.0.0-unpublished => ../theirmodule- 安装所有模块
go get .- 查看模块及模块的最新版本
go list -m -u all- 清理模块
go mod tidy工具依赖
类似于 npm 的devDependencies,只在开发/构建/测试时需要
go 1.24为go.mod引入了tool 指令,目前可以通过
go get -tool module
添加 tool 依赖
旧版本的 go,还得通过tools/tools.go 引用进行管理
测试与文档
- 函数以
Test_开头进行单元测试,以Benchmark_开头进行基准测试 对于file.go文件,我们可以创建file_test.go为其进行测试,比如file.go中有Add(),则可以在file_test.go中创建TestAdd()进行单元测试,或是创建BenchmarkAdd()进行基准测试,并通过以下命令行执行测试:
go test
# 执行所有子模块的测试
go test ./...
# 显示覆盖率
go test -cover
# 基准测试
go test -bench=. -benchmem ./...
# 生成内存分析文件
go test -bench=. -memprofile=mem.prof
# 生成CPU分析文件
go test -bench=. -cpuprofile=cpu.prof
# 检测数据竞争(并发编程)
go test -race ./...- 函数以
Example_编写 Example 在编写 API 文档时,如果试图为上述Add()添加用法示例,可以在file_test.go中创建ExampleAdd();如果是为整个包添加用法示例,可以创建一个Example()