基于 go-web 框架构建的 Web 应用示例项目。
通过 Go module 引入 go-web 作为依赖,框架基础设施(HTTP 服务器、数据库、Redis、缓存、日志、DI 装配等)全部由 go-web 提供,本项目仅关注业务逻辑。
mach/ ├── main.go # 入口,嵌入静态资源,调用 go-web 的 cmd.Start() ├── config/ │ ├── app.go # AppProvider 配置入口,注册自定义配置和迁移模型 │ └── autoload/ # 自定义配置项 │ ├── app.go # 应用名称、运行模式 │ ├── cache.go # 缓存驱动 │ ├── database.go # 数据库连接 │ ├── http.go # HTTP 监听地址、静态文件 │ ├── middleware.go # 中间件(CORS 等) │ ├── migration.go # 数据库迁移模型 │ ├── redis.go # Redis 连接 │ ├── router.go # 路由注册 │ └── static_fs.go # 嵌入式静态文件 ├── app/ │ ├── controller/ # 控制器 │ ├── service/ # 业务逻辑 │ ├── dao/ # 数据访问 │ ├── model/ # 数据模型 │ └── dto/ # 数据传输对象 ├── templates/ # HTML 模板 ├── static/ # 静态资源 ├── config.yaml.example # 配置文件示例 ├── Dockerfile # Docker 构建 └── go.mod # 模块定义
cp config.yaml.example config.yaml
go run main.go
服务默认监听 :8080,访问 http://localhost:8080 查看效果。
go build -o mach main.go ./mach
docker build -t mach . docker run -p 8080:8080 mach
编辑 config/autoload/router.go,在路由注册函数中添加新路由:
router.GET("/hello", deps.WrapHandler(controller.HelloController{}.GetHello))
在 app/controller/ 下新建文件,嵌入 go-web 的 BaseResponse 可直接使用 Success() / Error() 等响应方法:
package controller
import (
gowebCtrl "cnb.cool/mliev/open/go-web/app/controller"
"cnb.cool/mliev/open/go-web/pkg/interfaces"
"github.com/gin-gonic/gin"
)
type HelloController struct {
gowebCtrl.BaseResponse
}
func (r HelloController) GetHello(c *gin.Context, helper interfaces.HelperInterface) {
r.Success(c, gin.H{"message": "hello"})
}
在 config/autoload/migration.go 的 Get() 方法中添加模型:
func (receiver Migration) Get() []any {
return []any{
&model.User{},
}
}
编辑 config/autoload/middleware.go,在中间件列表中追加:
"http.middleware": []gin.HandlerFunc{
gowebMiddleware.CorsMiddleware(helper),
myCustomMiddleware(),
},
go-web 发布新版本后,只需更新依赖:
go get cnb.cool/mliev/open/go-web@latest go mod tidy
本地开发阶段使用 go.mod 中的 replace 指令指向本地路径,正式发布时移除即可。