~/blog/go-后端开发最佳实践.md
Go 后端开发最佳实践
分享 Go 后端开发的一些经验和最佳实践
Go 语言开发的一些心得。
项目结构
推荐的项目结构:
project/
├── cmd/ # 入口
├── internal/ # 内部模块
│ ├── handler/ # HTTP handlers
│ ├── service/ # 业务逻辑
│ └── store/ # 数据层
├── config/ # 配置
├── migrations/ # 数据库迁移
└── Dockerfile
依赖管理
# Go 1.25+ 使用 go.mod
go mod init github.com/your/project
go mod tidy
错误处理
// 不要忽略错误
if err != nil {
return fmt.Errorf("failed to do something: %w", err)
}
并发模式
// 使用 context 控制
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 使用 errgroup
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
return doSomething(ctx)
})
测试
func TestSomething(t *testing.T) {
// 使用 table-driven tests
tests := []struct{
name string
input int
want int
}{
{"case1", 1, 2},
{"case2", 2, 4},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := process(tt.input)
if got != tt.want {
t.Errorf("got %d, want %d", got, tt.want)
}
})
}
}
性能优化
- 使用
sync.Pool减少内存分配 - 避免频繁的字符串拼接,使用
strings.Builder - 使用
pprof分析性能瓶颈
更多内容待补充…