如何写出优雅的 Golang 代码
原文是一篇非常赞的工程总结,推荐。这里记录一些笔记
- 代码规范,
gofmt
,goimports
,golangci-lint
等,配合 CI 自动化 - 目录结构 Standard Go Project Layout
/pkg
可以被外部使用包模块/internal
私有模块,不可被外部使用- 不要有
/src
目录 /cmd
生成可执行文件/api
对外提供的 API 模块- 不要有
model/controller
这样的模块,按照职责拆分,面向接口开发
- 不要在
init
做资源初始化,比如 rpc/DB/Redis 等,因为 init 会被隐式执行,会默默初始化资源连接 - 推荐的做法是 Client + NewClient,显式初始化连接
- init 阶段适合做一些简单、轻量的前置条件判断,比如
flag
设置 - 使用 GoMock/sqlmock/httpmock/monkey 做 mock + 测试
Simple techniques to optimise Go programs 介绍了一些简单却非常高效的性能提升方法:
- Avoid using structures containing pointers as map keys for large maps, use ints or bytes
- Use strings.Builder to build up strings
- Use strconv instead of
fmt.Sprintf
Was this page helpful?