@@ -12,6 +12,8 @@ import (
12
12
"reflect"
13
13
"strings"
14
14
15
+ "github.com/gogf/gf/v2/errors/gcode"
16
+ "github.com/gogf/gf/v2/errors/gerror"
15
17
strip "github.com/grokify/html-strip-tags-go"
16
18
)
17
19
@@ -60,15 +62,26 @@ func SpecialCharsDecode(s string) string {
60
62
}
61
63
62
64
// SpecialCharsMapOrStruct automatically encodes string values/attributes for map/struct.
65
+ //
66
+ // Note that, if operation on struct, the given parameter `mapOrStruct` should be type of pointer to struct.
67
+ //
68
+ // For example:
69
+ // var m = map{}
70
+ // var s = struct{}{}
71
+ // OK: SpecialCharsMapOrStruct(m)
72
+ // OK: SpecialCharsMapOrStruct(&s)
73
+ // Error: SpecialCharsMapOrStruct(s)
63
74
func SpecialCharsMapOrStruct (mapOrStruct interface {}) error {
64
75
var (
65
76
reflectValue = reflect .ValueOf (mapOrStruct )
66
77
reflectKind = reflectValue .Kind ()
78
+ originalKind = reflectKind
67
79
)
68
80
for reflectValue .IsValid () && (reflectKind == reflect .Ptr || reflectKind == reflect .Interface ) {
69
81
reflectValue = reflectValue .Elem ()
70
82
reflectKind = reflectValue .Kind ()
71
83
}
84
+
72
85
switch reflectKind {
73
86
case reflect .Map :
74
87
var (
@@ -82,22 +95,43 @@ func SpecialCharsMapOrStruct(mapOrStruct interface{}) error {
82
95
reflectValue .SetMapIndex (key , reflect .ValueOf (SpecialChars (mapValue .String ())))
83
96
case reflect .Interface :
84
97
if mapValue .Elem ().Kind () == reflect .String {
85
- reflectValue .SetMapIndex (key , reflect .ValueOf (SpecialChars (mapValue .Elem ().String ())))
98
+ reflectValue .SetMapIndex (
99
+ key ,
100
+ reflect .ValueOf (SpecialChars (mapValue .Elem ().String ())),
101
+ )
86
102
}
103
+ default :
87
104
}
88
105
}
89
106
90
107
case reflect .Struct :
91
- var (
92
- fieldValue reflect.Value
93
- )
108
+ if originalKind != reflect .Ptr {
109
+ return gerror .NewCodef (
110
+ gcode .CodeInvalidParameter ,
111
+ `invalid input parameter type "%s", should be type of pointer to struct` ,
112
+ reflect .TypeOf (mapOrStruct ).String (),
113
+ )
114
+ }
115
+ var fieldValue reflect.Value
94
116
for i := 0 ; i < reflectValue .NumField (); i ++ {
95
117
fieldValue = reflectValue .Field (i )
96
118
switch fieldValue .Kind () {
97
119
case reflect .String :
98
- fieldValue .Set (reflect .ValueOf (SpecialChars (fieldValue .String ())))
120
+ fieldValue .Set (
121
+ reflect .ValueOf (
122
+ SpecialChars (fieldValue .String ()),
123
+ ),
124
+ )
125
+ default :
99
126
}
100
127
}
128
+
129
+ default :
130
+ return gerror .NewCodef (
131
+ gcode .CodeInvalidParameter ,
132
+ `invalid input parameter type "%s"` ,
133
+ reflect .TypeOf (mapOrStruct ).String (),
134
+ )
101
135
}
102
136
return nil
103
137
}
0 commit comments