-
Notifications
You must be signed in to change notification settings - Fork 20
/
webhook.go
227 lines (191 loc) · 6.69 KB
/
webhook.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package flows
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httputil"
"strings"
"github.com/nyaruka/goflow/excellent/types"
)
// WebhookStatus represents the status of a WebhookRequest
type WebhookStatus string
const (
// WebhookStatusSuccess represents that the webhook was successful
WebhookStatusSuccess WebhookStatus = "success"
// WebhookStatusConnectionError represents that the webhook had a connection error
WebhookStatusConnectionError WebhookStatus = "connection_error"
// WebhookStatusResponseError represents that the webhook response had a non 2xx status code
WebhookStatusResponseError WebhookStatus = "response_error"
)
func (r WebhookStatus) String() string {
return string(r)
}
// WebhookCall describes a call made to an external service. It has several properties which can be accessed in expressions:
//
// * `status` the status of the webhook - one of "success", "connection_error" or "response_error"
// * `status_code` the status code of the response
// * `body` the body of the response
// * `json` the parsed JSON response (if response body was JSON)
// * `json.[key]` sub-elements of the parsed JSON response
// * `request` the raw request made, including headers
// * `response` the raw response received, including headers
//
// Examples:
//
// @run.webhook.status_code -> 200
// @run.webhook.json.results.0.state -> WA
//
// @context webhook
type WebhookCall struct {
url string
method string
status WebhookStatus
statusCode int
request string
response string
body string
}
// MakeWebhookCall fires the passed in http request, returning any errors encountered. RequestResponse is always set
// regardless of any errors being set
func MakeWebhookCall(session Session, request *http.Request) (*WebhookCall, error) {
response, requestDump, err := session.HTTPClient().DoWithDump(request)
if err != nil {
w, _ := newWebhookCallFromError(request, requestDump, err)
return w, err
}
defer response.Body.Close()
return newWebhookCallFromResponse(requestDump, response)
}
// URL returns the full URL
func (w *WebhookCall) URL() string { return w.url }
// Status returns the response status message
func (w *WebhookCall) Status() WebhookStatus { return w.status }
// StatusCode returns the response status code
func (w *WebhookCall) StatusCode() int { return w.statusCode }
// Request returns the request trace
func (w *WebhookCall) Request() string { return w.request }
// Response returns the response trace
func (w *WebhookCall) Response() string { return w.response }
// Body returns the response body
func (w *WebhookCall) Body() string { return w.body }
// JSON returns the response as a JSON fragment
func (w *WebhookCall) JSON() types.XValue { return types.JSONToXValue([]byte(w.body)) }
// Resolve resolves the given key when this webhook is referenced in an expression
func (w *WebhookCall) Resolve(key string) types.XValue {
switch key {
case "body":
return types.NewXText(w.Body())
case "json":
return w.JSON()
case "url":
return types.NewXText(w.URL())
case "request":
return types.NewXText(w.Request())
case "response":
return types.NewXText(w.Response())
case "status":
return types.NewXText(string(w.Status()))
case "status_code":
return types.NewXNumberFromInt(w.StatusCode())
}
return types.NewXResolveError(w, key)
}
// Reduce is called when this object needs to be reduced to a primitive
func (w *WebhookCall) Reduce() types.XPrimitive {
return types.NewXText(w.body)
}
// ToXJSON is called when this type is passed to @(json(...))
func (w *WebhookCall) ToXJSON() types.XText {
return types.ResolveKeys(w, "body", "json", "url", "request", "response", "status", "status_code").ToXJSON()
}
var _ types.XValue = (*WebhookCall)(nil)
var _ types.XResolvable = (*WebhookCall)(nil)
// newWebhookCallFromError creates a new webhook call based on the passed in http request and error (when we received no response)
func newWebhookCallFromError(r *http.Request, requestTrace string, requestError error) (*WebhookCall, error) {
return &WebhookCall{
url: r.URL.String(),
request: requestTrace,
status: WebhookStatusConnectionError,
body: requestError.Error(),
}, nil
}
// newWebhookCallFromResponse creates a new RequestResponse based on the passed in http Response
func newWebhookCallFromResponse(requestTrace string, r *http.Response) (*WebhookCall, error) {
var err error
w := &WebhookCall{
url: r.Request.URL.String(),
statusCode: r.StatusCode,
request: requestTrace,
}
// set our status based on our status code
if w.statusCode/100 == 2 {
w.status = WebhookStatusSuccess
} else {
w.status = WebhookStatusResponseError
}
// figure out if our Response is something that looks like text from our headers
isText := false
contentType := r.Header.Get("Content-Type")
if strings.Contains(contentType, "text") ||
strings.Contains(contentType, "json") ||
strings.Contains(contentType, "utf") ||
strings.Contains(contentType, "javascript") ||
strings.Contains(contentType, "xml") {
isText = true
}
// only dump the whole body if this looks like text
response, err := httputil.DumpResponse(r, isText)
if err != nil {
return w, err
}
w.response = string(response)
if isText {
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return w, err
}
w.body = strings.TrimSpace(string(bodyBytes))
} else {
// no body for non-text responses but add it to our Response log so users know why
w.response = w.response + "\nNon-text body, ignoring"
}
return w, nil
}
//------------------------------------------------------------------------------------------
// JSON Encoding / Decoding
//------------------------------------------------------------------------------------------
type webhookCallEnvelope struct {
URL string `json:"url"`
Status WebhookStatus `json:"status"`
StatusCode int `json:"status_code"`
Body string `json:"body"`
Request string `json:"request"`
Response string `json:"response"`
}
// UnmarshalJSON unmarshals a request response from the given JSON
func (w *WebhookCall) UnmarshalJSON(data []byte) error {
var envelope webhookCallEnvelope
var err error
err = json.Unmarshal(data, &envelope)
if err != nil {
return err
}
w.url = envelope.URL
w.status = envelope.Status
w.statusCode = envelope.StatusCode
w.request = envelope.Request
w.response = envelope.Response
w.body = envelope.Body
return nil
}
// MarshalJSON marshals this request response into JSON
func (r *WebhookCall) MarshalJSON() ([]byte, error) {
return json.Marshal(&webhookCallEnvelope{
URL: r.url,
Status: r.status,
StatusCode: r.statusCode,
Request: r.request,
Response: r.response,
Body: r.body,
})
}