请求输入-默认值绑定

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

我们来看一个示例以便更好介绍。

参数对象定义

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方法执行参数获取和对象初始化。