-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdto.go
619 lines (538 loc) · 13.3 KB
/
dto.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// Copyright (c) 2018 Senseye Ltd. All rights reserved.
// Use of this source code is governed by the MIT License that can be found in the LICENSE file.
package mbgo
import (
"encoding/json"
"errors"
"fmt"
"net"
"reflect"
"strings"
)
func parseClientSocket(s string) (ip net.IP, err error) {
parts := strings.Split(s, ":")
ipStr := strings.Join(parts[0:len(parts)-1], ":")
ip = net.ParseIP(ipStr)
if ip == nil {
err = fmt.Errorf("invalid IP address: %s", ipStr)
}
return
}
func toMapValues(q map[string][]string) map[string]interface{} {
if q == nil {
return nil
}
out := make(map[string]interface{}, len(q))
for k, ss := range q {
if len(ss) == 0 {
continue
} else if len(ss) == 1 {
out[k] = ss[0]
} else {
out[k] = ss
}
}
return out
}
func fromMapValues(q map[string]interface{}) (map[string][]string, error) {
if q == nil {
return nil, nil
}
out := make(map[string][]string, len(q))
for k, v := range q {
switch typ := v.(type) {
case string:
out[k] = []string{typ}
case []interface{}:
ss := make([]string, len(typ))
for i, elem := range typ {
s, ok := elem.(string)
if !ok {
return nil, errors.New("invalid query key array subtype")
}
ss[i] = s
}
out[k] = ss
default:
return nil, fmt.Errorf("invalid query key type: %#v", typ)
}
}
return out, nil
}
type httpRequestDTO struct {
RequestFrom string `json:"requestFrom,omitempty"`
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Query map[string]interface{} `json:"query,omitempty"`
Headers map[string]interface{} `json:"headers,omitempty"`
Body interface{} `json:"body,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
}
// MarshalJSON satisfies the json.Marshaler interface.
func (r HTTPRequest) MarshalJSON() ([]byte, error) {
dto := httpRequestDTO{
RequestFrom: "",
Method: r.Method,
Path: r.Path,
Query: toMapValues(r.Query),
Headers: toMapValues(r.Headers),
Body: r.Body,
Timestamp: r.Timestamp,
}
if r.RequestFrom != nil {
dto.RequestFrom = r.RequestFrom.String()
}
return json.Marshal(dto)
}
// UnmarshalJSON satisfies the json.Unmarshaler interface.
func (r *HTTPRequest) UnmarshalJSON(b []byte) error {
var v httpRequestDTO
err := json.Unmarshal(b, &v)
if err != nil {
return err
}
if v.RequestFrom != "" {
r.RequestFrom, err = parseClientSocket(v.RequestFrom)
if err != nil {
return nil
}
}
r.Method = v.Method
r.Path = v.Path
r.Query, err = fromMapValues(v.Query)
if err != nil {
return nil
}
r.Headers, err = fromMapValues(v.Headers)
if err != nil {
return nil
}
r.Body = v.Body
r.Timestamp = v.Timestamp
return nil
}
type httpResponseDTO struct {
StatusCode int `json:"statusCode,omitempty"`
Headers map[string]interface{} `json:"headers,omitempty"`
Body interface{} `json:"body,omitempty"`
Mode string `json:"_mode,omitempty"`
}
// MarshalJSON satisfies the json.Marshaler interface.
func (r HTTPResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(httpResponseDTO{
StatusCode: r.StatusCode,
Headers: toMapValues(r.Headers),
Body: r.Body,
Mode: r.Mode,
})
}
// UnmarshalJSON satisfies the json.Unmarshaler interface.
func (r *HTTPResponse) UnmarshalJSON(b []byte) error {
var v httpResponseDTO
err := json.Unmarshal(b, &v)
if err != nil {
return err
}
r.StatusCode = v.StatusCode
r.Headers, err = fromMapValues(v.Headers)
if err != nil {
return err
}
r.Body = v.Body
r.Mode = v.Mode
return nil
}
type tcpRequestDTO struct {
RequestFrom string `json:"requestFrom,omitempty"`
Data string `json:"data,omitempty"`
}
// MarshalJSON satisfies the json.Marshaler interface.
func (r TCPRequest) MarshalJSON() ([]byte, error) {
dto := tcpRequestDTO{
RequestFrom: "",
Data: r.Data,
}
if r.RequestFrom != nil {
dto.RequestFrom = r.RequestFrom.String()
}
return json.Marshal(dto)
}
// UnmarshalJSON satisfies the json.Unmarshaler interface.
func (r *TCPRequest) UnmarshalJSON(b []byte) error {
var v tcpRequestDTO
err := json.Unmarshal(b, &v)
if err != nil {
return err
}
if v.RequestFrom != "" {
r.RequestFrom, err = parseClientSocket(v.RequestFrom)
if err != nil {
return err
}
}
r.Data = v.Data
return err
}
type tcpResponseDTO struct {
Data string `json:"data"`
}
// MarshalJSON satisfies the json.Marshaler interface.
func (r TCPResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(tcpResponseDTO(r))
}
// UnmarshalJSON satisfies the json.Unmarshaler interface.
func (r *TCPResponse) UnmarshalJSON(b []byte) error {
var v tcpResponseDTO
err := json.Unmarshal(b, &v)
if err != nil {
return err
}
r.Data = v.Data
return nil
}
const (
// Predicate parameter keys for internal use.
paramCaseSensitive = "caseSensitive"
paramExcept = "except"
paramJSONPath = "jsonpath"
paramXPath = "xpath"
)
type predicateDTO map[string]json.RawMessage
// MarshalJSON satisfies the json.Marshaler interface.
func (p Predicate) MarshalJSON() ([]byte, error) {
dto := predicateDTO{}
// marshal request based on type
switch t := p.Request.(type) {
case json.Marshaler:
b, err := t.MarshalJSON()
if err != nil {
return nil, err
}
dto[p.Operator] = b
case []Predicate:
preds := make([]json.RawMessage, len(t))
for i, sub := range t {
b, err := sub.MarshalJSON()
if err != nil {
return nil, err
}
preds[i] = b
}
b, err := json.Marshal(preds)
if err != nil {
return nil, err
}
dto[p.Operator] = b
case string:
b, err := json.Marshal(t)
if err != nil {
return nil, err
}
dto[p.Operator] = b
default:
return nil, fmt.Errorf("unsupported predicate request type: %v",
reflect.TypeOf(t).String())
}
if p.JSONPath != nil {
b, err := json.Marshal(p.JSONPath)
if err != nil {
return nil, err
}
dto[paramJSONPath] = b
}
if p.CaseSensitive {
b, err := json.Marshal(p.CaseSensitive)
if err != nil {
return nil, err
}
dto[paramCaseSensitive] = b
}
return json.Marshal(dto)
}
// UnmarshalJSON satisfies the json.Unmarshaler interface.
func (p *Predicate) UnmarshalJSON(b []byte) error {
var dto predicateDTO
err := json.Unmarshal(b, &dto)
if err != nil {
return err
}
// Handle and delete parameters from the DTO map before we check the
// operator so that we can enforce only one operator exists in the map.
if b, ok := dto[paramCaseSensitive]; ok {
err = json.Unmarshal(b, &p.CaseSensitive)
if err != nil {
return err
}
delete(dto, paramCaseSensitive)
}
if b, ok := dto[paramJSONPath]; ok {
err = json.Unmarshal(b, &p.JSONPath)
if err != nil {
return err
}
delete(dto, paramJSONPath)
}
// Ignore 'except' and 'xpath' parameters for now.
delete(dto, paramExcept)
delete(dto, paramXPath)
if len(dto) < 1 {
return errors.New("predicate should only have a single operator")
}
for key, b := range dto {
p.Operator = key
switch key {
// Interpret the request as a string containing JavaScript if the
// inject operator is used.
case "inject":
var js string
err = json.Unmarshal(b, &js)
if err != nil {
return err
}
p.Request = js
// Slice of predicates
case "and", "or":
var ps []Predicate
err = json.Unmarshal(b, &ps)
if err != nil {
return err
}
p.Request = ps
// Single predicate
case "not":
var v Predicate
err = json.Unmarshal(b, &v)
if err != nil {
return err
}
p.Request = v
// Otherwise we have a request object.
default:
p.Request = b // defer unmarshaling until protocol is known
}
}
return nil
}
const (
keyBehaviors = "_behaviors"
)
// MarshalJSON satisfies the json.Marshaler interface.
func (r Response) MarshalJSON() ([]byte, error) {
dto := make(map[string]json.RawMessage)
m, ok := r.Value.(json.Marshaler)
if !ok {
return nil, errors.New("response value must implement json.Marshaler")
}
b, err := m.MarshalJSON()
if err != nil {
return nil, err
}
dto[r.Type] = b
if r.Behaviors != nil {
behaviors, err := json.Marshal(r.Behaviors)
if err != nil {
return nil, err
}
dto[keyBehaviors] = behaviors
}
return json.Marshal(dto)
}
// UnmarshalJSON satisfies the json.Unmarshaler interface.
func (r *Response) UnmarshalJSON(b []byte) error {
var dto map[string]json.RawMessage
err := json.Unmarshal(b, &dto)
if err != nil {
return err
}
// Handle and delete behaviors from the DTO map before we check the
// type so that we can enforce only one type exists in the map.
if b, ok := dto[keyBehaviors]; ok {
behaviors := new(Behaviors)
err = json.Unmarshal(b, behaviors)
if err != nil {
return err
}
delete(dto, keyBehaviors)
r.Behaviors = behaviors
}
for key, b := range dto {
r.Type = key
r.Value = b // defer unmarshaling until protocol is known
}
return nil
}
type stubDTO struct {
Predicates []Predicate `json:"predicates,omitempty"`
Responses []Response `json:"responses"`
}
// MarshalJSON satisfies the json.Marshaler interface.
func (s Stub) MarshalJSON() ([]byte, error) {
return json.Marshal(stubDTO(s))
}
// UnmarshalJSON satisfies the json.Unmarshaler interface.
func (s *Stub) UnmarshalJSON(b []byte) error {
var dto stubDTO
err := json.Unmarshal(b, &dto)
if err != nil {
return err
}
s.Predicates = dto.Predicates
s.Responses = dto.Responses
return nil
}
type imposterRequestDTO struct {
Proto string `json:"protocol"`
Port int `json:"port,omitempty"`
Name string `json:"name,omitempty"`
RecordRequests bool `json:"recordRequests,omitempty"`
AllowCORS bool `json:"allowCORS,omitempty"`
DefaultResponse json.RawMessage `json:"defaultResponse,omitempty"`
Stubs []json.RawMessage `json:"stubs,omitempty"`
}
// MarshalJSON satisfies the json.Marshaler interface.
func (imp Imposter) MarshalJSON() ([]byte, error) {
dto := imposterRequestDTO{
Proto: imp.Proto,
Port: imp.Port,
Name: imp.Name,
RecordRequests: imp.RecordRequests,
AllowCORS: imp.AllowCORS,
DefaultResponse: nil,
Stubs: nil,
}
if imp.DefaultResponse != nil {
jm, ok := imp.DefaultResponse.(json.Marshaler)
if !ok {
return nil, errors.New("default response must implemented json.Marshaler")
}
b, err := jm.MarshalJSON()
if err != nil {
return nil, err
}
dto.DefaultResponse = b
}
if n := len(imp.Stubs); n > 0 {
dto.Stubs = make([]json.RawMessage, n)
for i, stub := range imp.Stubs {
b, err := stub.MarshalJSON()
if err != nil {
return nil, err
}
dto.Stubs[i] = b
}
}
return json.Marshal(dto)
}
type imposterResponseDTO struct {
Port int `json:"port"`
Proto string `json:"protocol"`
Name string `json:"name,omitempty"`
RequestCount int `json:"numberOfRequests,omitempty"`
Stubs []json.RawMessage `json:"stubs,omitempty"`
Requests []json.RawMessage `json:"requests,omitempty"`
}
func getRequestUnmarshaler(proto string) (json.Unmarshaler, error) {
var um json.Unmarshaler
switch proto {
case "http":
um = &HTTPRequest{}
case "tcp":
um = &TCPRequest{}
default:
return nil, fmt.Errorf("unsupported protocol: %s", proto)
}
return um, nil
}
func unmarshalPredicateRecurse(proto string, p *Predicate) error {
switch v := p.Request.(type) {
case json.RawMessage:
um, err := getRequestUnmarshaler(proto)
if err != nil {
return err
}
if err = um.UnmarshalJSON(v); err != nil {
return err
}
p.Request = um
case Predicate:
if err := unmarshalPredicateRecurse(proto, &v); err != nil {
return err
}
case []Predicate:
for i := range v {
if err := unmarshalPredicateRecurse(proto, &v[i]); err != nil {
return err
}
}
}
return nil
}
func getResponseUnmarshaler(proto string) (json.Unmarshaler, error) {
var um json.Unmarshaler
switch proto {
case "http":
um = &HTTPResponse{}
case "tcp":
um = &TCPResponse{}
default:
return nil, fmt.Errorf("unsupported protocol: %s", proto)
}
return um, nil
}
// UnmarshalJSON satisfies the json.Unmarshaler interface.
func (imp *Imposter) UnmarshalJSON(b []byte) error {
var dto imposterResponseDTO
err := json.Unmarshal(b, &dto)
if err != nil {
return err
}
imp.Port = dto.Port
imp.Proto = dto.Proto
imp.Name = dto.Name
imp.RequestCount = dto.RequestCount
if n := len(dto.Stubs); n > 0 {
imp.Stubs = make([]Stub, n)
for i, b := range dto.Stubs {
var s Stub
err = json.Unmarshal(b, &s)
if err != nil {
return err
}
for i := range s.Predicates {
err = unmarshalPredicateRecurse(imp.Proto, &s.Predicates[i])
if err != nil {
return err
}
}
for i, r := range s.Responses {
if raw, ok := r.Value.(json.RawMessage); ok {
um, err := getResponseUnmarshaler(imp.Proto)
if err != nil {
return err
}
err = um.UnmarshalJSON(raw)
if err != nil {
return err
}
s.Responses[i].Value = um
}
}
imp.Stubs[i] = s
}
}
if n := len(dto.Requests); n > 0 {
imp.Requests = make([]interface{}, n)
for i, b := range dto.Requests {
um, err := getRequestUnmarshaler(imp.Proto)
if err != nil {
return err
}
err = um.UnmarshalJSON(b)
if err != nil {
return err
}
imp.Requests[i] = um
}
}
return nil
}