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

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

参数对象定义

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

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

参数对象使用

  1. // @summary 展示文章首页
  2. // @tags 前台-文章
  3. // @produce html
  4. // @param cate query int false "栏目ID"
  5. // @param page query int false "分页号码"
  6. // @param size query int false "分页数量"
  7. // @param sort query string false "排序方式"
  8. // @router /article [GET]
  9. // @success 200 {string} html "页面HTML"
  10. func (a *articleApi) Index(r *ghttp.Request) {
  11. var (
  12. data *define.ContentServiceGetListReq
  13. )
  14. if err := r.Parse(&data); err != nil {
  15. service.View.Render500(r, model.View{
  16. Error: err.Error(),
  17. })
  18. }
  19. data.Type = model.ContentTypeArticle
  20. if getListRes, err := service.Content.GetList(r.Context(), data); err != nil {
  21. service.View.Render500(r, model.View{
  22. Error: err.Error(),
  23. })
  24. } else {
  25. service.View.Render(r, model.View{
  26. ContentType: data.Type,
  27. Data: getListRes,
  28. Title: service.View.GetTitle(r.Context(), &define.ViewServiceGetTitleReq{
  29. ContentType: data.Type,
  30. CategoryId: data.CategoryId,
  31. }),
  32. })
  33. }
  34. }

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

Content Menu