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

成都创新互联公司是一家专注于网站建设、网站制作与策划设计,迁安网站建设哪家好?成都创新互联公司做网站,专注于网站建设十多年,网设计领域的专业建站公司;建站业务涵盖:迁安等地区。迁安做网站价格咨询:028-86922220
我们来看一个示例以便更好理解。
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方法执行参数获取和对象初始化。