-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathencoder.go
101 lines (81 loc) · 1.67 KB
/
encoder.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package encoder
import (
"bytes"
"encoding/json"
"encoding/xml"
"reflect"
)
type Encoder interface {
Encode(v interface{}) ([]byte, error)
}
type Filter interface {
Filter() interface{}
}
func Must(data []byte, err error) []byte {
if err != nil {
panic(err)
}
return data
}
type JsonEncoder struct {
PrettyPrint bool
PrintNull bool // if true, empty object will be 'null', '{}' instead (by default)
}
func (e JsonEncoder) Encode(obj interface{}) ([]byte, error) {
obj, _ = filter(obj)
if obj == nil && !e.PrintNull {
obj = struct{}{}
}
if e.PrettyPrint {
return json.MarshalIndent(obj, "", " ")
} else {
return json.Marshal(obj)
}
}
type XmlEncoder struct {
PrettyPrint bool
}
func (e XmlEncoder) Encode(obj interface{}) ([]byte, error) {
var buffer bytes.Buffer
var err error
var b []byte
obj, _ = filter(obj)
if _, err := buffer.Write([]byte(xml.Header)); err != nil {
return []byte{}, err
}
if e.PrettyPrint {
b, err = xml.MarshalIndent(obj, "", " ")
} else {
b, err = xml.Marshal(obj)
}
if err != nil {
return []byte{}, err
}
buffer.Write(b)
return buffer.Bytes(), nil
}
func filter(obj interface{}) (interface{}, error) {
v := reflect.ValueOf(obj)
k := v.Kind()
if k == reflect.Ptr && v.IsNil() {
return nil, nil
}
if k == reflect.Array || k == reflect.Slice {
result := make([]interface{}, 0)
for i := 0; i < v.Len(); i++ {
obj := v.Index(i).Interface()
if f, ok := obj.(Filter); ok {
result = append(result, f.Filter())
} else {
result = append(result, obj)
}
}
return result, nil
} else {
if f, ok := obj.(Filter); ok {
return f.Filter(), nil
}
return obj, nil
}
return nil, nil
}