项目结构
项目结构
go-web 的目录划分严格区分框架核心 (pkg/) 和应用代码 (app/、config/、cmd/)。框架核心理论上不需要修改,业务开发只在应用代码层进行。
顶层目录
go-web/
├── main.go # 程序入口,embed 模板与静态资源
├── go.mod / go.sum # Go 模块定义
├── config.yaml.example # 配置文件示例
├── init.sh # 项目初始化脚本(替换模块路径)
├── Dockerfile # 多阶段构建镜像
├── app/ # 应用层代码
├── cmd/ # CLI 入口与启动逻辑
├── config/ # 配置加载与 AppProvider
├── migrations/ # SQL 迁移文件目录
├── pkg/ # 框架核心
├── static/ # 静态资源(go:embed)
└── templates/ # 模板文件(go:embed)app/ 应用层
业务代码全部位于此目录,遵循经典分层模型。
app/
├── controller/ # 控制器,接受 RouterContextInterface
│ ├── base_response.go # 统一响应封装(Success / Error)
│ ├── health_controller.go
│ └── index_controller.go
├── service/ # 服务层,封装业务逻辑
├── dao/ # 数据访问层(GORM 调用)
├── model/ # 数据模型(GORM 结构体)
├── dto/ # 数据传输对象(请求/响应结构体)
├── constants/ # 常量与错误码
│ └── errors.go
└── middleware/ # 业务中间件
└── cors_middleware.gocmd/ 入口与启动
cmd/
├── run.go # cmd.Start():信号监听 + 装配 + 启动 Server
├── options.go # Functional Options(WithApp/WithTemplateFs/...)
└── migrate/ # 数据库迁移 CLI(独立 main)
└── main.goconfig/ 配置
config/
├── app.go # 默认 AppProvider 实现:Assemblies() / Servers()
├── config.go # 列出所有 InitConfig 实现
└── autoload/ # 各领域的配置默认值
├── app.go # app.app_name / app.mode
├── cache.go # cache.driver
├── database.go # database.driver / host / port / ...
├── http.go # http.load_static / static_mode / static_dir
├── middleware.go # http.middleware([]MiddlewareFunc)
├── migration.go # database.migration.dir
├── redis.go # redis.host / port / password / db
├── router.go # http.router(注册路由的 callback)
└── static_fs.go # static.fs(map[string]embed.FS)pkg/ 框架核心
pkg/
├── container/ # DI 容器(Provider/SimpleProvider/LazyProvider)
├── contract/ # 服务契约(常用类型别名)
├── driver/ # 泛型驱动管理器 Manager[T]
├── helper/ # 全局访问器(GetDatabase / GetLogger / ...)
├── interfaces/ # AppProvider / Assembly / Server / InitConfig
└── server/ # 各基础设施实现
├── cache/ # 缓存(redis / memory / none 驱动)
├── config/ # 配置 Provider(从 InitConfig 聚合)
├── database/ # 数据库(mysql / postgresql / sqlite / memory)
├── env/ # 环境变量与 yaml 读取(Viper)
├── http_server/ # HTTP 服务(基于 Gin)
│ ├── interfaces/ # RouterInterface / RouterContextInterface
│ ├── impl/ # Gin 适配 + 正则路由 dispatch
│ └── service/ # HttpServer 启动器
├── logger/ # 日志(development / production)
├── migration/ # 数据库迁移 Server(自动 goose.Up)
├── redis/ # Redis 客户端封装
└── reload/ # 热重载信号通道资源目录
static/—— 通过//go:embed static/**编译进二进制的静态文件templates/—— 通过//go:embed templates/**编译进二进制的模板文件migrations/—— SQL 迁移脚本,运行时由 Goose 顺序执行
关于框架核心与业务的边界
| 目录 | 是否常改 | 说明 |
|---|---|---|
app/ |
✅ 频繁 | 所有业务代码、控制器、模型 |
config/autoload/ |
✅ 偶尔 | 增加新配置键、路由、中间件 |
cmd/ |
🚫 一般不改 | 启动流程稳定 |
pkg/ |
🚫 一般不改 | 框架核心,改动会影响所有项目 |
如果你需要扩展框架本身,例如添加一种新的数据库驱动,推荐在自己的项目里通过 Extend() 注册而不是修改 pkg/server/database/driver/。详见「Driver Manager」章节。