Skip to content

Commit 348543c

Browse files
jiukerguozhi.li
and
guozhi.li
authored
fix: *string(nil) not equal &string #152
Signed-off-by: guozhi.li <[email protected]> Co-authored-by: guozhi.li <[email protected]>
1 parent c9f1d67 commit 348543c

File tree

2 files changed

+47
-3
lines changed

2 files changed

+47
-3
lines changed

values.go

+15-3
Original file line numberDiff line numberDiff line change
@@ -161,10 +161,22 @@ func ReadOnly(ctx context.Context, path, in string, data interface{}) *errors.Va
161161
func Required(path, in string, data interface{}) *errors.Validation {
162162
val := reflect.ValueOf(data)
163163
if val.IsValid() {
164-
if reflect.DeepEqual(reflect.Zero(val.Type()).Interface(), val.Interface()) {
165-
return errors.Required(path, in, data)
164+
typ := reflect.TypeOf(data)
165+
switch typ.Kind() {
166+
case reflect.Pointer:
167+
if val.IsNil() {
168+
return errors.Required(path, in, data)
169+
}
170+
if reflect.DeepEqual(reflect.Zero(val.Elem().Type()).Interface(), val.Elem().Interface()) {
171+
return errors.Required(path, in, data)
172+
}
173+
return nil
174+
default:
175+
if reflect.DeepEqual(reflect.Zero(val.Type()).Interface(), val.Interface()) {
176+
return errors.Required(path, in, data)
177+
}
178+
return nil
166179
}
167-
return nil
168180
}
169181
return errors.Required(path, in, data)
170182
}

values_test.go

+32
Original file line numberDiff line numberDiff line change
@@ -195,22 +195,54 @@ func TestValues_ValidateRequired(t *testing.T) {
195195
path := "test"
196196
in := "body"
197197

198+
emptyString := ""
199+
emptyStringStruct := struct {
200+
A *string
201+
}{
202+
A: &emptyString,
203+
}
204+
205+
emptyNumber := 0
206+
emptyNumberStruct := struct {
207+
A *int
208+
}{
209+
A: &emptyNumber,
210+
}
211+
198212
RequiredFail := []interface{}{
199213
"",
200214
0,
201215
nil,
216+
emptyStringStruct.A,
217+
emptyNumberStruct.A,
202218
}
203219

204220
for _, v := range RequiredFail {
205221
err = Required(path, in, v)
206222
assert.Error(t, err)
207223
}
208224

225+
notEmptyString := "bla"
226+
notEmptyStringStruct := struct {
227+
A *string
228+
}{
229+
A: &notEmptyString,
230+
}
231+
232+
notEmptyNumber := 1
233+
notEmptyNumberStruct := struct {
234+
A *int
235+
}{
236+
A: &notEmptyNumber,
237+
}
238+
209239
RequiredSuccess := []interface{}{
210240
" ",
211241
"bla-bla-bla",
212242
2,
213243
[]interface{}{21, []int{}, "testString"},
244+
notEmptyStringStruct.A,
245+
notEmptyNumberStruct.A,
214246
}
215247

216248
for _, v := range RequiredSuccess {

0 commit comments

Comments
 (0)