/
filtering.go
79 lines (64 loc) · 1.69 KB
/
filtering.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
package morganfield
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"reflect"
)
// Optional validation functionality
type Validator interface {
Validate()
}
// Marshals any object into string
func Marshal(in interface{}) (string, error) {
arr, err := json.Marshal(in)
return string(arr), err
}
// Unmarshals any string into object
func UnMarshal(in string, out interface{}) (interface{}, error) {
err := json.Unmarshal([]byte(in), out)
return out, err
}
// filters input json
func filter_input_json(r *http.Request, s Service_Definition) (string, error) {
defer r.Body.Close()
return filter_object_json(&r.Body, s.In_Object)
}
// filters output json
func filter_output_json(r *http.Response, s Service_Definition) (string, error) {
defer r.Body.Close()
return filter_object_json(&r.Body, s.Out_Object)
}
// filters JSON by unmarshaling & marshaling it
func filter_object_json(in *io.ReadCloser, o interface{}) (string, error) {
var filterd string
if o == nil {
return filterd, fmt.Errorf("filter_object_json: no Object set!")
}
// Build new o object
tgtType := reflect.ValueOf(o).Type()
target := reflect.New(tgtType).Interface()
// Read the string representation
bs, err := ioutil.ReadAll(*in)
if err != nil {
panic(fmt.Sprintf("filter_object_json: %v", err))
}
tr := string(bs)
ino, err := UnMarshal(tr, target)
if err != nil {
panic(fmt.Sprintf("filter_object_json: %v", err))
}
// Optional extra validation
if validd, ok := ino.(Validator); ok {
validd.Validate()
}
// Marshal the result back to string
cleand, err := Marshal(target)
if err != nil {
panic(fmt.Sprintf("filter_object_json: %v", err))
}
filterd = string(cleand)
return filterd, nil
}