-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpatch.go
87 lines (84 loc) · 2.24 KB
/
patch.go
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package core
import (
"bytes"
"context"
"encoding/json"
"net/http"
"reflect"
"strings"
)
func IsPatch(ctx context.Context) bool {
m := ctx.Value(Method)
if m != nil && m.(string) == Patch {
return true
}
return false
}
func BuildMapAndStruct(r *http.Request, interfaceBody interface{}, options ...http.ResponseWriter) (map[string]interface{}, error) {
buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
s := buf.String()
body := make(map[string]interface{})
er1 := json.NewDecoder(strings.NewReader(s)).Decode(&body)
if er1 != nil {
return nil, er1
}
er2 := json.NewDecoder(strings.NewReader(s)).Decode(interfaceBody)
if er2 != nil {
if len(options) > 0 && options[0] != nil {
http.Error(options[0], er2.Error(), http.StatusBadRequest)
}
return nil, er2
}
return body, nil
}
func BodyToJsonMap(r *http.Request, structBody interface{}, body map[string]interface{}, jsonIds []string, mapIndex map[string]int, options ...func(context.Context, interface{}) error) (map[string]interface{}, error) {
var buildToPatch func(context.Context, interface{}) error
if len(options) > 0 && options[0] != nil {
buildToPatch = options[0]
}
if buildToPatch != nil {
var er0 error
er0 = buildToPatch(r.Context(), structBody)
if er0 != nil {
return nil, er0
}
inRec, er1 := json.Marshal(structBody)
if er1 != nil {
return nil, er1
}
var model map[string]interface{}
json.Unmarshal(inRec, &model)
for k, v := range model {
stringKind := reflect.TypeOf(v).String()
if (v != nil && stringKind == "float64" && v.(float64) != 0) || (v != nil && stringKind != "float64" && v != "") {
body[k] = v
}
}
}
valueOfReq := reflect.ValueOf(structBody)
if valueOfReq.Kind() == reflect.Ptr {
valueOfReq = reflect.Indirect(valueOfReq)
}
for _, jsonName := range jsonIds {
if i, ok := mapIndex[jsonName]; ok && i >= 0 {
v, _, er4 := GetValue(structBody, i)
if er4 == nil {
body[jsonName] = v
}
}
}
result := make(map[string]interface{})
for keyJsonName, _ := range body {
v2 := body[keyJsonName]
if v2 == nil {
result[keyJsonName] = v2
} else if i, ok := mapIndex[keyJsonName]; ok && i >= 0 {
v, _, er4 := GetValue(structBody, i)
if er4 == nil {
result[keyJsonName] = v
}
}
}
return result, nil
}