-
Notifications
You must be signed in to change notification settings - Fork 5
/
types.go
110 lines (88 loc) · 2.3 KB
/
types.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
package caddy
import (
"encoding/json"
"fmt"
)
// These types map to caddy types, but allow us to use them more effectively as
// we've circumvented their heavy usage of json.RawMessage
type route struct {
Group string `json:"group,omitempty"`
MatcherSets []matcherSet `json:"match,omitempty"`
Handlers handlers `json:"handle,omitempty"`
Terminal bool `json:"terminal,omitempty"`
}
type matcherSet struct {
Host []string `json:"host,omitempty"`
Path []string `json:"path,omitempty"`
}
type handlers []handler
func (h handlers) MarshalJSON() ([]byte, error) {
out := []map[string]interface{}{}
for _, handler := range h {
data, err := json.Marshal(handler)
if err != nil {
return nil, err
}
jsonMap := map[string]interface{}{}
if err := json.Unmarshal(data, &jsonMap); err != nil {
return nil, err
}
jsonMap["handler"] = handler.HandlerName()
out = append(out, jsonMap)
}
return json.Marshal(out)
}
func (h *handlers) UnmarshalJSON(dataBytes []byte) error {
out := handlers{}
raw := []json.RawMessage{}
if err := json.Unmarshal(dataBytes, &raw); err != nil {
return err
}
for _, rawHandler := range raw {
handlerIdentity := struct {
Handler string `json:"handler"`
}{}
if err := json.Unmarshal(rawHandler, &handlerIdentity); err != nil {
return err
}
switch handlerIdentity.Handler {
case "reverse_proxy":
value := reverseProxyHandler{}
if err := json.Unmarshal(rawHandler, &value); err != nil {
return err
}
out = append(out, value)
case "static_response":
value := staticResponseHandler{}
if err := json.Unmarshal(rawHandler, &value); err != nil {
return err
}
out = append(out, value)
default:
return fmt.Errorf(
"unknown handler type '%s'", handlerIdentity.Handler,
)
}
}
*h = out
return nil
}
type handler interface {
HandlerName() string
}
type reverseProxyHandler struct {
Upstreams []upstream `json:"upstreams,omitempty"`
}
type upstream struct {
Dial string `json:"dial,omitempty"`
}
func (rph reverseProxyHandler) HandlerName() string {
return "reverse_proxy"
}
type staticResponseHandler struct {
Body string `json:"body,omitempty"`
StatusCode string `json:"status_code,omitempty"`
}
func (rph staticResponseHandler) HandlerName() string {
return "static_response"
}