数据结构支持设置默认值能力

This commit is contained in:
白茶清欢 2025-03-21 23:01:41 +08:00
parent 9859cba993
commit d973b5c5fc
4 changed files with 20 additions and 9 deletions

View File

@ -14,7 +14,7 @@ import (
const (
TagErrMsg = "err" // json结构体中, 错误信息 tag 字段
TagValidate = "validator" // json结构体中, 验证规则 rule 字段
TagDefaultValue = "d" // json结构体中默认值标签
TagDefaultValue = "default" // json结构体中默认值标签
)
// Rule 规则定义

1
go.mod
View File

@ -7,6 +7,7 @@ require (
git.zhangdeman.cn/zhangdeman/dynamic-struct v0.0.0-20250319072714-eab2a7abde63
git.zhangdeman.cn/zhangdeman/json_filter v0.0.0-20250321103029-786c03293a28
git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20241223084948-de2e49144fcd
github.com/creasty/defaults v1.8.0
github.com/go-playground/validator/v10 v10.25.0
github.com/tidwall/gjson v1.18.0
github.com/tidwall/sjson v1.2.5

2
go.sum
View File

@ -22,6 +22,8 @@ github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394 h1:OYA+5W64v3OgClL+IrOD63t4i/RW7RqrAVl9LTZ9UqQ=
github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394/go.mod h1:Q8n74mJTIgjX4RBBcHnJ05h//6/k6foqmgE45jTQtxg=
github.com/creasty/defaults v1.8.0 h1:z27FJxCAa0JKt3utc0sCImAEb+spPucmKoOdLHvHYKk=
github.com/creasty/defaults v1.8.0/go.mod h1:iGzKe6pbEHnpMPtfDXZEr0NVxWnPTjb1bbDy08fPzYM=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=

View File

@ -15,6 +15,7 @@ import (
dynamicStructGenerate "git.zhangdeman.cn/zhangdeman/dynamic-struct"
"git.zhangdeman.cn/zhangdeman/json_filter/gjson_hack"
"git.zhangdeman.cn/zhangdeman/serialize"
"github.com/creasty/defaults"
"github.com/go-playground/validator/v10"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
@ -101,6 +102,10 @@ func (h *handle) Run() ([]byte, error) {
if err := serialize.JSON.UnmarshalWithNumber([]byte(h.formatVal), &val); nil != err {
return nil, err
}
if err := defaults.Set(&val); nil != err {
// 默认值设置失败
return nil, err
}
if err := validatorInstance.Struct(val); nil != err {
return nil, GetValidateErr(val, err, TagErrMsg)
}
@ -231,6 +236,9 @@ func (h *handle) generateTag(field StructField) string {
// 验证规则tag
tagList = append(tagList, fmt.Sprintf(`%s:"%s"`, TagValidate, strings.Join(validateRuleList, ",")))
// 默认值
if field.DefaultValue == "-" && (field.Type == consts.DataTypeString || field.Type == consts.DataTypeStringPtr) {
field.DefaultValue = ""
}
tagList = append(tagList, fmt.Sprintf(`%s:"%s"`, TagDefaultValue, field.DefaultValue))
return strings.Join(tagList, " ")
}