webexample 模块解析

webexample 是 goweb3 项目中 Web 开发的完整示例模块,展示了如何基于 goweb3 框架快速构建 RESTful API。


一、模块架构


plainText

webexample/
├── user_contact.go          # 实体模型(Model)
├── user_contact_init.go     # 实体依赖注入注册
├── ui_user_contact.go       # UI 请求封装(Request)
├── ui_user_contact_init.go  # UI 请求依赖注入注册
├── user_contact_ctl.go      # 控制器(Controller)
├── user_contact_ctl_init.go # 控制器依赖注入注册
└── webexample_test.go       # 测试用例

二、核心组件详解

1. UserContact - 实体模型

go

type UserContact struct {
    basedto.BaseEntity `json:"-" gorm:"-"`
    simplemodel.Model  // 继承基础模型(包含 id, created_at, updated_at, deleted_at)
    
    UserType      int    `json:"-"`           // 用户类型
    UserId        int64  `json:"userId,string"` // 用户ID
    FeishuWebHook string `json:"feishuWebHook"` // 飞书WebHook
    FeishuId      string `json:"feishuId"`      // 飞书ID
    WeixinQrUrl   string `json:"weixinQrUrl"`   // 微信二维码URL
}

必须实现的接口

方法 说明
PkeyName() 返回主键字段名
PkeyValue() 返回主键值
TableName() 返回表名
NewDao() 创建 DAO 实例

缓存支持


go

func (self *UserContact) ObjectKey() string {
    var keys = []any{
        ichubconfig.FindEnv(), "db", self.TableName(), self.PkeyValue(),
    }
    return strings.Join(gconv.SliceStr(keys), ":")  // 格式: env:db:user_contact:id
}
2. UiUserContact - UI 请求封装

go

type UiUserContact struct {
    basedto2.BaseEntity
    uiframe.UiSimpleQ[*UserContactReq, *UserContact]  // 泛型 UI 查询
}

type UserContactReq struct {
    UserId int64 `json:"userId,string"`
    Id     int64 `json:"id,string"`
}

查询条件构建


go

func (self *UiUserContact) initQuery() *UiUserContact {
    self.SetBeforeQuery(func() {
        self.BuildGeneralParams(self.PageDb)
        
        if self.Query.Id > 0 {
            self.DbEq("id", self.Query.Id)
        }
        if self.Query.UserId > 0 {
            self.DbEq("user_id", self.Query.UserId)
        }
        if self.Query.Id > 0 && self.Query.UserId > 0 {
            self.DbWhere("id = ? or user_id = ?", self.Query.Id, self.Query.UserId)
        }
    })
    return self
}

核心方法

方法 说明
UiList() 分页查询列表
List() 内部查询方法
UiSave2Result() 保存(新增/更新)
UiUpdate2Result() 更新
3. UserContactCtl - 控制器

go

type UserContactCtl struct {
    funchandler.FuncService  // 继承通用服务
    basedto.BaseEntitySingle // 单例基类
}

func (self *UserContactCtl) RegisterRoute(api *gin.RouterGroup) {
    api.POST("/example/user/contact/uilist", self.UiList)
    api.GET("/example/user/contact/uilist", self.UiList)
    api.POST("/example/user/contact/uisave", self.UiSave2Result)
    api.PUT("/example/user/contact/uiupdate", self.UiUpdate2Result)
    api.GET("/example/user/contact/findById/:id", self.FindById)
    api.DELETE("/example/user/contact/deleteById/:id", self.DeleteById)
}

API 路由表

HTTP 方法 路径 方法 说明
POST/GET /example/user/contact/uilist UiList 查询列表
POST/GET /example/user/contact/uisave UiSave2Result 保存(新增)
PUT/POST /example/user/contact/uiupdate UiUpdate2Result 更新
GET /example/user/contact/findById/:id FindById 根据ID查询
DELETE/POST /example/user/contact/deleteById/:id DeleteById 删除

三、数据流转流程


plainText

┌─────────────────────────────────────────────────────────────────┐
│                      webexample 数据流程                       │
├─────────────────────────────────────────────────────────────────┤
│                                                               │
│  HTTP 请求                                                     │
│       │                                                        │
│       ▼                                                        │
│  UserContactCtl.UiList(c)                                     │
│       │                                                        │
│       │  1. ParseBody(c, req) - 解析请求体                     │
│       │  2. req.UiList() - 调用业务方法                        │
│       ▼                                                        │
│  UiUserContact.UiList()                                        │
│       │                                                        │
│       │  1. List() - 构建查询                                  │
│       │  2. BuildRequestQuery() - 应用查询条件                 │
│       │  3. QueryModel() - 执行数据库查询                      │
│       ▼                                                        │
│  generaldao.BaseDao.QueryModel()                               │
│       │                                                        │
│       │  1. 构建 WHERE 条件                                    │
│       │  2. 执行 SQL 查询                                      │
│       │  3. 返回 PageResult                                    │
│       ▼                                                        │
│  pagemodel.PageResult                                          │
│       │                                                        │
│       ▼                                                        │
│  HTTP 响应                                                     │
│                                                               │
└─────────────────────────────────────────────────────────────────┘

四、依赖关系


plainText

webexample
    ├── goconfig/base/basedto           # 基础 DTO
    ├── goconfig/ichubconfig           # 配置管理
    ├── goconfig/ichublog/golog        # 日志
    ├── gotool/dbframe/uiframe         # UI 查询框架
    ├── goweb/generaldb/generaldao     # 通用 DAO
    ├── goweb/pagemodel                # 分页模型
    ├── goweb/webserver/funchandler    # 处理器基类
    ├── gin-gonic/gin                  # Web 框架
    └── gomini/minitest/testgin        # 测试框架

五、测试用例


go

func (self *TestWebExampleSuite) Test001_UiTrialTransList() {
    var url = "/api/v1/example/user/contact/UiList"
    var testframe = testgin.FindBeanGinTestframe().InitPost(url, FindBeanUserContactCtl().UiList)
    
    var req = FindBeanUiUserContact()
    req.Query.UserId = 1988166425163862016
    
    var ret = testframe.Post2PageResult(req)
    golog.Info(ret)
}

测试流程

  1. 初始化测试框架 testgin.FindBeanGinTestframe()
  2. 设置请求 URL 和处理方法
  3. 构建查询参数
  4. 执行 POST 请求并获取分页结果

六、代码生成模式

该模块遵循 goweb3 的 代码生成模式,文件命名约定:

文件类型 命名格式 示例
实体 {entity}.go user_contact.go
实体初始化 {entity}_init.go user_contact_init.go
UI 请求 ui_{entity}.go ui_user_contact.go
UI 请求初始化 ui_{entity}_init.go ui_user_contact_init.go
控制器 {entity}_ctl.go user_contact_ctl.go
控制器初始化 {entity}_ctl_init.go user_contact_ctl_init.go

七、总结

webexample 模块展示了 goweb3 框架中 标准 CRUD 接口的实现模式

特性 实现方式
分层架构 Model → UI Request → Controller
依赖注入 通过 FindBeanXxx() 获取单例
泛型支持 UiSimpleQ[Req, Entity] 类型安全
自动路由 RegisterRoute() 集中注册
统一响应 PageResult / IchubResult
测试友好 testgin 测试框架支持

这是 goweb3 项目中最典型的 Web 服务开发模板,可作为业务模块开发的参考范式

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐