-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_responses.go
More file actions
57 lines (52 loc) · 1.08 KB
/
validate_responses.go
File metadata and controls
57 lines (52 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package rest
import (
"reflect"
)
func ValidateResponse(errors error, code int) error {
errResponse := ErrFieldResp{
Meta: ErrMeta{
ErrCode: code,
},
Fields: []ErrField{},
}
v := reflect.ValueOf(errors)
switch v.Kind() {
// map[string]error
case reflect.Map:
if v.Type().Key().Kind() != reflect.String {
break
}
if !v.Type().Elem().Implements(reflect.TypeOf((*error)(nil)).Elem()) {
break
}
for _, k := range v.MapKeys() {
errResponse.AddError(k.String(), 0, v.MapIndex(k).Interface().(error).Error())
}
// []error
case reflect.Slice:
if v.Len() == 0 {
break
}
hasName := false
if v.Index(0).Kind() == reflect.Interface {
if v.Index(0).Elem().Kind() == reflect.Struct {
if v.Index(0).Elem().FieldByName("Name").IsValid() {
hasName = true
}
}
}
for i := 0; i < v.Len(); i++ {
e := v.Index(i)
if hasName {
errResponse.AddError(
e.Elem().FieldByName("Name").String(),
0,
e.Interface().(error).Error(),
)
} else {
errResponse.Add(e.Interface().(error).Error())
}
}
}
return errResponse
}