GoFrame 请求输入-默认值绑定

2022-04-13 15:38 更新

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


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号