1.15 Go项目工程化实践:项目结构、代码规范、依赖管理完整指南
引言
工程化是保证项目质量和可维护性的关键。本文将全面介绍Go项目的工程化实践,包括项目结构、代码规范、依赖管理、CI/CD等,帮助你构建高质量的Go项目。
一、项目结构
1.1 标准项目结构
myproject/ ├── cmd/ # 应用程序入口 │ ├── server/ │ │ └── main.go │ └── cli/ │ └── main.go ├── internal/ # 私有代码 │ ├── handler/ │ ├── service/ │ └── repository/ ├── pkg/ # 可被外部导入的包 │ ├── utils/ │ └── logger/ ├── api/ # API定义 │ └── openapi.yaml ├── configs/ # 配置文件 │ └── config.yaml ├── scripts/ # 脚本文件 │ └── build.sh ├── test/ # 测试数据 ├── docs/ # 文档 ├── .gitignore ├── .golangci.yml # 代码检查配置 ├── Makefile ├── go.mod ├── go.sum └── README.md1.2 项目结构说明
- cmd/: 应用程序的main函数
- internal/: 私有代码,外部无法导入
- pkg/: 可被外部项目导入的公共代码
- api/: API定义文件
- configs/: 配置文件
- scripts/: 构建、部署脚本
二、代码规范
2.1 命名规范
// 包名:小写,简短packagehttp// 公开函数:驼峰命名,首字母大写funcGetUser(idint)(*User,error)// 私有函数:驼峰命名,首字母小写funcgetUser(idint)(*User,error)// 常量:全大写,下划线分隔constMAX_RETRIES=3// 接口:通常以er结尾typeReaderinterface{Read([]byte)(int,error)}// 错误:以Error结尾typeValidationErrorstruct{Fieldstring}2.2 代码格式化
# 使用gofmt格式化gofmt./...# 使用goimports(自动整理imports)goinstallgolang.org/x/tools/cmd/goimports@latest goimports -w.2.3 代码检查
使用golangci-lint:
# 安装curl-sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh|sh-s -- -b$(goenvGOPATH)/bin v1.54.2# 运行检查golangci-lint run.golangci.yml配置:
linters:enable:-errcheck-gosimple-govet-ineffassign-staticcheck-unusedlinters-settings:errcheck:check-type-assertions:truecheck-blank:true三、依赖管理
3.1 go.mod最佳实践
module github.com/username/myprojectgo1.21require(github.com/gin-gonic/gin v1.9.1github.com/stretchr/testify v1.8.4)// 排除有问题的版本exclude github.com/gin-gonic/gin v1.9.0// 替换依赖(用于本地开发或fork)replace github.com/gin