-
Notifications
You must be signed in to change notification settings - Fork 361
/
endpoint.go
201 lines (155 loc) · 4.34 KB
/
endpoint.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package proxy
import (
"bytes"
"io"
"net/http"
"regexp"
"strings"
"time"
log "github.com/sirupsen/logrus"
"github.com/stripe/stripe-cli/pkg/websocket"
)
//
// Public types
//
// EndpointConfig contains the optional configuration parameters of an EndpointClient.
type EndpointConfig struct {
HTTPClient *http.Client
Log *log.Logger
ResponseHandler EndpointResponseHandler
// OutCh is the channel to send data and statuses to for processing in other packages
OutCh chan websocket.IElement
}
// EndpointResponseHandler handles a response from the endpoint.
type EndpointResponseHandler interface {
ProcessResponse(eventContext, string, *http.Response)
}
// EndpointResponseHandlerFunc is an adapter to allow the use of ordinary
// functions as response handlers. If f is a function with the
// appropriate signature, ResponseHandler(f) is a
// ResponseHandler that calls f.
type EndpointResponseHandlerFunc func(eventContext, string, *http.Response)
// ProcessResponse calls f(evtCtx, forwardURL, resp).
func (f EndpointResponseHandlerFunc) ProcessResponse(evtCtx eventContext, forwardURL string, resp *http.Response) {
f(evtCtx, forwardURL, resp)
}
// FailedToPostError describes a failure to send a POST request to an endpoint
type FailedToPostError struct {
Err error
}
func (f FailedToPostError) Error() string {
return f.Err.Error()
}
// EndpointClient is the client used to POST webhook requests to the local endpoint.
type EndpointClient struct {
// URL the client sends POST requests to
URL string
headers map[string]string
connect bool
events map[string]bool
// Optional configuration parameters
cfg *EndpointConfig
}
// SupportsEventType takes an event of a webhook and compares it to the internal
// list of supported events
func (c *EndpointClient) SupportsEventType(connect bool, eventType string) bool {
if connect != c.connect {
return false
}
// Endpoint supports all events, always return true
if c.events["*"] || c.events[eventType] {
return true
}
return false
}
// Post sends a message to the local endpoint.
func (c *EndpointClient) Post(evtCtx eventContext, body string, headers map[string]string) error {
c.cfg.Log.WithFields(log.Fields{
"prefix": "proxy.EndpointClient.Post",
}).Debug("Forwarding event to local endpoint")
req, err := http.NewRequest(http.MethodPost, c.URL, bytes.NewBuffer([]byte(body)))
if err != nil {
return err
}
for k, v := range headers {
req.Header.Add(k, v)
}
// add custom headers
for k, v := range c.headers {
if strings.ToLower(k) == "host" {
req.Host = v
} else {
req.Header.Add(k, v)
}
}
resp, err := c.cfg.HTTPClient.Do(req)
if err != nil {
c.cfg.OutCh <- websocket.ErrorElement{
Error: FailedToPostError{Err: err},
}
return err
}
defer resp.Body.Close()
c.cfg.ResponseHandler.ProcessResponse(evtCtx, c.URL, resp)
return nil
}
//
// Public functions
//
// NewEndpointClient returns a new EndpointClient.
func NewEndpointClient(url string, headers []string, connect bool, events []string, cfg *EndpointConfig) *EndpointClient {
if cfg == nil {
cfg = &EndpointConfig{}
}
if cfg.Log == nil {
cfg.Log = &log.Logger{Out: io.Discard}
}
if cfg.HTTPClient == nil {
cfg.HTTPClient = &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Timeout: defaultTimeout,
}
}
if cfg.ResponseHandler == nil {
cfg.ResponseHandler = EndpointResponseHandlerFunc(func(eventContext, string, *http.Response) {})
}
return &EndpointClient{
URL: url,
headers: convertToMapAndSanitize(headers),
connect: connect,
events: convertToMap(events),
cfg: cfg,
}
}
//
// Private constants
//
const (
defaultTimeout = 30 * time.Second
)
//
// Private functions
//
func convertToMap(events []string) map[string]bool {
eventsMap := make(map[string]bool)
for _, event := range events {
eventsMap[event] = true
}
return eventsMap
}
func convertToMapAndSanitize(headers []string) map[string]string {
reg := regexp.MustCompile("[\x00-\x1f]+")
headerMap := make(map[string]string)
for _, header := range headers {
header = reg.ReplaceAllString(header, "")
splitHeader := strings.SplitN(header, ":", 2)
headerKey := strings.TrimSpace(splitHeader[0])
headerVal := strings.TrimSpace(splitHeader[1])
if headerKey != "" {
headerMap[headerKey] = headerVal
}
}
return headerMap
}