-
Notifications
You must be signed in to change notification settings - Fork 351
/
json.go
114 lines (93 loc) · 2.24 KB
/
json.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
102
103
104
105
106
107
108
109
110
111
112
113
114
package eskip
import (
"bytes"
"encoding/json"
)
type jsonNameArgs struct {
Name string `json:"name"`
Args []interface{} `json:"args,omitempty"`
}
type jsonBackend struct {
Type string `json:"type"`
Address string `json:"address,omitempty"`
Algorithm string `json:"algorithm,omitempty"`
Endpoints []string `json:"endpoints,omitempty"`
}
type jsonRoute struct {
ID string `json:"id,omitempty"`
Backend *jsonBackend `json:"backend,omitempty"`
Predicates []*Predicate `json:"predicates,omitempty"`
Filters []*Filter `json:"filters,omitempty"`
}
func newJSONRoute(r *Route) *jsonRoute {
cr := Canonical(r)
jr := &jsonRoute{
ID: cr.Id,
Predicates: cr.Predicates,
Filters: cr.Filters,
}
if cr.BackendType != NetworkBackend || cr.Backend != "" {
jr.Backend = &jsonBackend{
Type: cr.BackendType.String(),
Address: cr.Backend,
Algorithm: cr.LBAlgorithm,
Endpoints: cr.LBEndpoints,
}
}
return jr
}
func marshalJSONNoEscape(v interface{}) ([]byte, error) {
var buf bytes.Buffer
e := json.NewEncoder(&buf)
e.SetEscapeHTML(false)
if err := e.Encode(v); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (f *Filter) MarshalJSON() ([]byte, error) {
return marshalJSONNoEscape(&jsonNameArgs{Name: f.Name, Args: f.Args})
}
func (p *Predicate) MarshalJSON() ([]byte, error) {
return marshalJSONNoEscape(&jsonNameArgs{Name: p.Name, Args: p.Args})
}
func (r *Route) MarshalJSON() ([]byte, error) {
return marshalJSONNoEscape(newJSONRoute(r))
}
func (r *Route) UnmarshalJSON(b []byte) error {
jr := &jsonRoute{}
if err := json.Unmarshal(b, jr); err != nil {
return err
}
r.Id = jr.ID
var bts string
if jr.Backend != nil {
bts = jr.Backend.Type
}
bt, err := BackendTypeFromString(bts)
if err != nil {
return err
}
r.BackendType = bt
switch bt {
case NetworkBackend:
if jr.Backend != nil {
r.Backend = jr.Backend.Address
}
case LBBackend:
r.LBAlgorithm = jr.Backend.Algorithm
r.LBEndpoints = jr.Backend.Endpoints
if len(r.LBEndpoints) == 0 {
r.LBEndpoints = nil
}
}
r.Filters = jr.Filters
if len(r.Filters) == 0 {
r.Filters = nil
}
r.Predicates = jr.Predicates
if len(r.Predicates) == 0 {
r.Predicates = nil
}
return nil
}