Categories: GoFrame 教程

GoFrame 请求输入-默认值绑定

从v1.15版本开始,​Request​请求对象支持通过​struct tag​的方式为输入对象的属性绑定默认值。默认值的​struct tag​名称为​d​(也可以使用​default​)。

我们来看一个示例以便更好理解。

参数对象定义

type ContentServiceGetListReq struct {
 Type       string                                    // 内容模型
 CategoryId uint   `p:"cate"`                         // 栏目ID
 Page       int    `d:"1"  v:"min:0#分页号码错误"`      // 分页号码
 Size       int    `d:"10" v:"max:50#分页数量最大50条"` // 分页数量,最大50
 Sort       int    // 排序类型(0:最新, 默认。1:活跃, 2:热度)
}

这个是一个查询内容列表请求的参数接受对象,其中我们通过​d​的标签为属性​Page​和​Size​指定了默认值,当这两个参数不传递时,默认为1和10,表示分页从第1页开始,每页查询数量为10。

参数对象使用

// @summary 展示文章首页
// @tags    前台-文章
// @produce html
// @param   cate query int    false "栏目ID"
// @param   page query int    false "分页号码"
// @param   size query int    false "分页数量"
// @param   sort query string false "排序方式"
// @router  /article [GET]
// @success 200 {string} html "页面HTML"
func (a *articleApi) Index(r *ghttp.Request) {
 var (
  data *define.ContentServiceGetListReq
 )
 if err := r.Parse(&data); err != nil {
  service.View.Render500(r, model.View{
   Error: err.Error(),
  })
 }
 data.Type = model.ContentTypeArticle
 if getListRes, err := service.Content.GetList(r.Context(), data); err != nil {
  service.View.Render500(r, model.View{
   Error: err.Error(),
  })
 } else {
  service.View.Render(r, model.View{
   ContentType: data.Type,
   Data:        getListRes,
   Title: service.View.GetTitle(r.Context(), &define.ViewServiceGetTitleReq{
    ContentType: data.Type,
    CategoryId:  data.CategoryId,
   }),
  })
 }
}

这个一个​MVC​设计模式中的一个文章查询接口,该接口负责查询内容列表的请求并渲染展示文章列表页面。可以看到这里使用了​Parse​方法直接获取并转换客户端提交的参数到​ContentServiceGetListReq​对象上。当然,这里也可以使用​GetStruct​方法执行参数获取和对象初始化。

admin

这个人很懒,什么都没有留下~

Share
Published by
admin

Recent Posts

聊聊vue3中的defineProps

在Vue 3中,defineP…

1 周 ago

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

2 周 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

3 周 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

4 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

1 月 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

1 月 ago