-
Notifications
You must be signed in to change notification settings - Fork 78
/
trigger.go
283 lines (229 loc) · 6.57 KB
/
trigger.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package rest
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/TIBCOSoftware/flogo-contrib/trigger/rest/cors"
"github.com/TIBCOSoftware/flogo-lib/core/data"
"github.com/TIBCOSoftware/flogo-lib/core/trigger"
"github.com/TIBCOSoftware/flogo-lib/logger"
"github.com/julienschmidt/httprouter"
)
const (
REST_CORS_PREFIX = "REST_TRIGGER"
)
// log is the default package logger
var log = logger.GetLogger("trigger-flogo-rest")
var validMethods = []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}
// RestTrigger REST trigger struct
type RestTrigger struct {
metadata *trigger.Metadata
//runner action.Runner
server *Server
config *trigger.Config
//handlers []*handler.Handler
}
//NewFactory create a new Trigger factory
func NewFactory(md *trigger.Metadata) trigger.Factory {
return &RestFactory{metadata: md}
}
// RestFactory REST Trigger factory
type RestFactory struct {
metadata *trigger.Metadata
}
//New Creates a new trigger instance for a given id
func (t *RestFactory) New(config *trigger.Config) trigger.Trigger {
return &RestTrigger{metadata: t.metadata, config: config}
}
// Metadata implements trigger.Trigger.Metadata
func (t *RestTrigger) Metadata() *trigger.Metadata {
return t.metadata
}
func (t *RestTrigger) Initialize(ctx trigger.InitContext) error {
router := httprouter.New()
if t.config.Settings == nil {
return fmt.Errorf("no Settings found for trigger '%s'", t.config.Id)
}
if _, ok := t.config.Settings["port"]; !ok {
return fmt.Errorf("no Port found for trigger '%s' in settings", t.config.Id)
}
addr := ":" + t.config.GetSetting("port")
pathMap := make(map[string]string)
// Init handlers
for _, handler := range ctx.GetHandlers() {
err := validateHandler(t.config.Id, handler)
if err != nil {
return err
}
method := strings.ToUpper(handler.GetStringSetting("method"))
path := handler.GetStringSetting("path")
log.Debugf("Registering handler [%s: %s]", method, path)
if _, ok := pathMap[path]; !ok {
pathMap[path] = path
router.OPTIONS(path, handleCorsPreflight) // for CORS
}
//router.OPTIONS(path, handleCorsPreflight) // for CORS
router.Handle(method, path, newActionHandler(t, handler))
}
log.Debugf("Configured on port %s", t.config.Settings["port"])
t.server = NewServer(addr, router)
return nil
}
func (t *RestTrigger) Start() error {
return t.server.Start()
}
// Stop implements util.Managed.Stop
func (t *RestTrigger) Stop() error {
return t.server.Stop()
}
// Handles the cors preflight request
func handleCorsPreflight(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
log.Infof("Received [OPTIONS] request to CorsPreFlight: %+v", r)
c := cors.New(REST_CORS_PREFIX, log)
c.HandlePreflight(w, r)
}
// IDResponse id response object
type IDResponse struct {
ID string `json:"id"`
}
func newActionHandler(rt *RestTrigger, handler *trigger.Handler) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.Infof("Received request for id '%s'", rt.config.Id)
c := cors.New(REST_CORS_PREFIX, log)
c.WriteCorsActualRequestHeaders(w)
pathParams := make(map[string]string)
for _, param := range ps {
pathParams[param.Key] = param.Value
}
queryValues := r.URL.Query()
queryParams := make(map[string]string, len(queryValues))
header := make(map[string]string, len(r.Header))
for key, value := range r.Header {
header[key] = strings.Join(value, ",")
}
for key, value := range queryValues {
queryParams[key] = strings.Join(value, ",")
}
triggerData := map[string]interface{}{
"params": pathParams,
"pathParams": pathParams,
"queryParams": queryParams,
"header": header,
}
// Check the HTTP Header Content-Type
contentType := r.Header.Get("Content-Type")
switch contentType {
case "application/x-www-form-urlencoded":
buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
s := buf.String()
m, err := url.ParseQuery(s)
content := make(map[string]interface{}, 0)
if err != nil {
log.Errorf("Error while parsing query string: %s", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
}
for key, val := range m {
if len(val) == 1 {
content[key] = val[0]
} else {
content[key] = val[0]
}
}
triggerData["content"] = content
default:
var content interface{}
err := json.NewDecoder(r.Body).Decode(&content)
if err != nil {
switch {
case err == io.EOF:
// empty body
//todo should handler say if content is expected?
case err != nil:
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
triggerData["content"] = content
}
results, err := handler.Handle(context.Background(), triggerData)
var replyData interface{}
var replyCode int
if len(results) != 0 {
dataAttr, ok := results["data"]
if ok {
replyData = dataAttr.Value()
}
codeAttr, ok := results["code"]
if ok {
replyCode, _ = data.CoerceToInteger(codeAttr.Value())
}
}
if err != nil {
log.Debugf("REST Trigger Error: %s", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if replyData != nil {
if replyCode == 0 {
replyCode = 200
}
switch t := replyData.(type) {
case string:
var v interface{}
err := json.Unmarshal([]byte(t), &v)
if err != nil {
//Not a json
w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
} else {
//Json
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
}
w.WriteHeader(replyCode)
_, err = w.Write([]byte(t))
if err != nil {
log.Error(err)
}
return
default:
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(replyCode)
if err := json.NewEncoder(w).Encode(replyData); err != nil {
log.Error(err)
}
return
}
}
if replyCode > 0 {
w.WriteHeader(replyCode)
} else {
w.WriteHeader(http.StatusOK)
}
}
}
////////////////////////////////////////////////////////////////////////////////////////
// Utils
func validateHandler(triggerId string, handler *trigger.Handler) error {
method := handler.GetStringSetting("method")
if method == "" {
return fmt.Errorf("no method specified in handler for trigger '%s'", triggerId)
}
if !stringInList(strings.ToUpper(method), validMethods) {
return fmt.Errorf("invalid method '%s' specified in handler for trigger '%s'", method, triggerId)
}
//validate path
return nil
}
func stringInList(str string, list []string) bool {
for _, value := range list {
if value == str {
return true
}
}
return false
}