Compare commits

...

4 Commits

Author SHA1 Message Date
wenzuochao 4d8a89852b fixToMapError 2020-04-03 10:26:35 +08:00
wenzuochao 60574a9378 modify tomap 2020-04-03 10:17:26 +08:00
wenzuochao 2a388c0108 update checkMaxLength 2020-03-20 15:21:05 +08:00
wenzuochao 268f040e48 modify checkMaxLength 2020-03-20 13:05:33 +08:00
2 changed files with 23 additions and 5 deletions
+14 -1
View File
@@ -558,8 +558,14 @@ func Merge(args ...interface{}) map[string]string {
}
func ToMap(args ...interface{}) map[string]interface{} {
isNotNil := false
finalArg := make(map[string]interface{})
for _, obj := range args {
if obj == nil {
continue
}
isNotNil = true
switch obj.(type) {
case map[string]string:
arg := obj.(map[string]string)
@@ -618,6 +624,9 @@ func ToMap(args ...interface{}) map[string]interface{} {
}
}
if !isNotNil {
return nil
}
return finalArg
}
@@ -848,7 +857,11 @@ func checkMaxLength(valueField reflect.Value, tag string) error {
if err != nil {
return err
}
if maxLength < valueField.Len() {
length := valueField.Len()
if valueField.Kind().String() == "string" {
length = strings.Count(valueField.String(), "") - 1
}
if maxLength < length {
errMsg := fmt.Sprintf("Length of %s is more than %d", valueField.String(), maxLength)
return errors.New(errMsg)
}
+9 -4
View File
@@ -47,6 +47,7 @@ var runtimeObj = map[string]interface{}{
type validateTest struct {
Num *int `json:"num" require:"true"`
Name *string `json:"name" maxLength:"4"`
Str *string `json:"str" pattern:"^[a-d]*$" maxLength:"4"`
Test *errLength `json:"test"`
List []*string `json:"list" pattern:"^[a-d]*$" maxLength:"4"`
@@ -273,13 +274,13 @@ func TestToMap(t *testing.T) {
invalidStr := "sdfdg"
result = ToMap(invalidStr)
utils.AssertEqual(t, result, map[string]interface{}{})
utils.AssertEqual(t, map[string]interface{}{}, result)
result = ToMap(10)
utils.AssertEqual(t, result, map[string]interface{}{})
utils.AssertEqual(t, map[string]interface{}{}, result)
result = ToMap(nil)
utils.AssertEqual(t, map[string]interface{}{}, result)
utils.AssertNil(t, result)
}
func Test_Retryable(t *testing.T) {
@@ -541,7 +542,7 @@ func Test_validate(t *testing.T) {
utils.AssertNil(t, err)
num := 1
str0, str1 := "acc", "abcddd"
str0, str1 := "abc", "abcddd"
val := &validateTest{
Num: &num,
Str: &str0,
@@ -559,6 +560,10 @@ func Test_validate(t *testing.T) {
err = validate(reflect.ValueOf(val))
utils.AssertEqual(t, "num should be setted", err.Error())
val.Name = String("最大长度")
err = validate(reflect.ValueOf(val))
utils.AssertEqual(t, "num should be setted", err.Error())
val.Num = &num
val.Str = &str0
val.List = []*string{&str1}