-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathencoder.go
465 lines (383 loc) · 9.23 KB
/
encoder.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
package sugar
import (
"bytes"
"encoding/json"
"encoding/xml"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"os"
"reflect"
"strconv"
"strings"
)
// EncoderGroup is a set of encoders.
type EncoderGroup []Encoder
// Add appends encoders to the encoder group.
func (e *EncoderGroup) Add(encoders ...Encoder) {
*e = append(*e, encoders...)
}
var (
Stringify = ToString
)
type List []interface{}
// L is an alias for List.
type L = List
type Map map[string]interface{}
// M is an alias for Map.
type M = Map
type Header Map
// H is an alias for Header.
type H = Header
type Cookie Map
// C is an alias for Cookie.
type C = Cookie
type Path Map
// P is an alias for Path.
type P = Path
type Query Map
// Q is an alias for Query.
type Q = Query
type Form Map
// F is an alias for Form.
type F = Form
type Json struct {
Payload interface{}
}
// J is an alias for Json.
type J = Json
type Xml struct {
Payload interface{}
}
// X is an alias for Xml.
type X = Xml
type User struct {
Name, Password string
}
// U is an alias for User.
type U = User
type MultiPart Map
// MP is an alias for MultiPart.
type MP = MultiPart
// RequestContext keeps values for an encoder.
type RequestContext struct {
Request *http.Request
Response *http.Response
Params []interface{}
Param interface{}
ParamIndex int
}
// Encoder converts a request context into request params.
// It returns an error if any error occurs during encoding.
// Call chain.Next() to propagate context.
type Encoder interface {
Encode(context *RequestContext, chain *EncoderChain) error
}
// EncoderChain keeps a set of encoders.
type EncoderChain struct {
context *RequestContext
encoders []Encoder
index int
}
// Next propagates context to next encoder.
// It returns EncoderNotFound if current encoder is the last one.
func (c *EncoderChain) Next() error {
if c.index < len(c.encoders) {
c.index++
return c.encoders[c.index-1].Encode(c.context, c)
}
return EncoderNotFound
}
func (c *EncoderChain) reset() *EncoderChain {
c.index = 0
return c
}
// Add adds encoders to an encoder chain.
func (c *EncoderChain) Add(encoders ...Encoder) *EncoderChain {
c.encoders = append(c.encoders, encoders...)
return c
}
// NewEncoderChain initializes a new encoder chain with given request context and encoders.
func NewEncoderChain(context *RequestContext, encoders ...Encoder) *EncoderChain {
chain := &EncoderChain{context: context, index: 0}
chain.reset().Add(encoders...)
return chain
}
// PathEncoder encodes Path{} params.
type PathEncoder struct {
}
// Encode encodes Path{} params.
func (e *PathEncoder) Encode(context *RequestContext, chain *EncoderChain) error {
pathParams, ok := context.Param.(Path)
if !ok {
return chain.Next()
}
req := context.Request
for i := 0; i < len(req.URL.Path); i++ {
if string(req.URL.Path[i]) == ":" {
j := i + 1
for ; j < len(req.URL.Path); j++ {
s := string(req.URL.Path[j])
if s == "/" {
break
}
}
key := req.URL.Path[i+1 : j]
value := pathParams[key]
req.URL.Path = strings.ReplaceAll(req.URL.Path, req.URL.Path[i:j], Stringify(value))
}
}
return nil
}
// QueryEncoder encodes Query{} params.
type QueryEncoder struct {
}
// Encode encodes Query{} params.
func (e *QueryEncoder) Encode(context *RequestContext, chain *EncoderChain) error {
queryParams, ok := context.Param.(Query)
if !ok {
return chain.Next()
}
req := context.Request
q := req.URL.Query()
for k, v := range queryParams {
switch reflect.TypeOf(v).Kind() {
case reflect.Array, reflect.Slice:
foreach(v, func(i interface{}) {
q.Add(k, Stringify(i))
})
default:
q.Add(k, Stringify(v))
}
}
req.URL.RawQuery = strings.ReplaceAll(q.Encode(), "+", "%20")
return nil
}
// HeaderEncoder encodes Header{} params.
type HeaderEncoder struct {
}
// Encode encodes Header{} params.
func (e *HeaderEncoder) Encode(context *RequestContext, chain *EncoderChain) error {
headerParams, ok := context.Param.(Header)
if !ok {
return chain.Next()
}
for k, v := range headerParams {
context.Request.Header.Add(k, Stringify(v))
}
return nil
}
// FormEncoder encodes Form{} params.
type FormEncoder struct {
}
// Encode encodes Form{} params.
func (e *FormEncoder) Encode(context *RequestContext, chain *EncoderChain) error {
formParams, ok := context.Param.(Form)
if !ok {
return chain.Next()
}
form := url.Values{}
for k, v := range formParams {
switch reflect.TypeOf(v).Kind() {
case reflect.Array, reflect.Slice:
foreach(v, func(i interface{}) {
form.Add(k, Stringify(i))
})
default:
form.Add(k, Stringify(v))
}
}
req := context.Request
req.PostForm = form
err := req.ParseForm()
if err != nil {
return err
}
if _, ok := req.Header[ContentType]; !ok {
req.Header.Set(ContentType, ContentTypeForm)
}
return nil
}
// JsonEncoder encodes Json{} params.
type JsonEncoder struct {
}
// Encode encodes Json{} params.
func (e *JsonEncoder) Encode(context *RequestContext, chain *EncoderChain) error {
jsonParams, ok := context.Param.(Json)
if !ok {
return chain.Next()
}
var b []byte
var err error
switch x := jsonParams.Payload.(type) {
case []byte:
b, err = json.RawMessage(x).MarshalJSON()
case string:
b, err = json.RawMessage(x).MarshalJSON()
default:
b, err = json.Marshal(x)
}
if err != nil {
return err
}
req := context.Request
req.Body = ioutil.NopCloser(bytes.NewReader(b))
if _, ok := req.Header[ContentType]; !ok {
req.Header.Set(ContentType, ContentTypeJsonUtf8)
}
return nil
}
// CookieEncoder encodes Cookie{} params.
type CookieEncoder struct {
}
// Encode encodes Cookie{} params.
func (e *CookieEncoder) Encode(context *RequestContext, chain *EncoderChain) error {
cookieParams, ok := context.Param.(Cookie)
if !ok {
return chain.Next()
}
for k, v := range cookieParams {
context.Request.AddCookie(&http.Cookie{Name: k, Value: Stringify(v)})
}
return nil
}
// BasicAuthEncoder encodes User{} params.
type BasicAuthEncoder struct {
}
// Encode encodes User{} params.
func (e *BasicAuthEncoder) Encode(context *RequestContext, chain *EncoderChain) error {
authParams, ok := context.Param.(User)
if !ok {
return chain.Next()
}
context.Request.SetBasicAuth(authParams.Name, authParams.Password)
return nil
}
// MultiPartEncoder encodes MultiPart{} params.
type MultiPartEncoder struct {
}
// Encode encodes MultiPart{} params.
func (e *MultiPartEncoder) Encode(context *RequestContext, chain *EncoderChain) error {
multiPartParams, ok := context.Param.(MultiPart)
if !ok {
return chain.Next()
}
b := &bytes.Buffer{}
w := multipart.NewWriter(b)
defer w.Close()
for k, v := range multiPartParams {
switch x := v.(type) {
case *os.File:
if err := writeFile(w, k, x.Name(), x); err != nil {
return err
}
default:
if err := w.WriteField(k, Stringify(v)); err != nil {
return err
}
}
}
req := context.Request
req.Body = ioutil.NopCloser(b)
if _, ok := req.Header[ContentType]; !ok {
req.Header.Set(ContentType, w.FormDataContentType())
}
return nil
}
func writeFile(w *multipart.Writer, fieldName, fileName string, file io.Reader) error {
fileWriter, err := w.CreateFormFile(fieldName, fileName)
if err != nil {
return err
}
if _, err = io.Copy(fileWriter, file); err != nil {
return err
}
return nil
}
// PlainTextEncoder encodes string params.
type PlainTextEncoder struct {
}
// Encode encodes string params.
func (e *PlainTextEncoder) Encode(context *RequestContext, chain *EncoderChain) error {
textParams, ok := context.Param.(string)
if !ok {
return chain.Next()
}
b := &bytes.Buffer{}
b.WriteString(textParams)
req := context.Request
req.Body = ioutil.NopCloser(b)
if _, ok := req.Header[ContentType]; !ok {
req.Header.Set(ContentType, ContentTypePlainText)
}
return nil
}
// XmlEncoder encodes Xml{} params.
type XmlEncoder struct {
}
// Encode encodes Xml{} params.
func (e *XmlEncoder) Encode(context *RequestContext, chain *EncoderChain) error {
xmlParams, ok := context.Param.(Xml)
if !ok {
return chain.Next()
}
var b []byte
var err error
switch x := xmlParams.Payload.(type) {
case string:
b = []byte(x)
default:
b, err = xml.Marshal(x)
}
if err != nil {
return err
}
req := context.Request
req.Body = ioutil.NopCloser(bytes.NewReader(b))
if _, ok := req.Header[ContentType]; !ok {
req.Header.Set(ContentType, ContentTypeXmlUtf8)
}
return nil
}
func ToString(v interface{}) string {
var s string
switch x := v.(type) {
case bool:
s = strconv.FormatBool(x)
case uint:
s = strconv.FormatUint(uint64(x), 10)
case uint8:
s = strconv.FormatUint(uint64(x), 10)
case uint16:
s = strconv.FormatUint(uint64(x), 10)
case uint32:
s = strconv.FormatUint(uint64(x), 10)
case uint64:
s = strconv.FormatUint(x, 10)
case int:
s = strconv.FormatInt(int64(x), 10)
case int8:
s = strconv.FormatInt(int64(x), 10)
case int16:
s = strconv.FormatInt(int64(x), 10)
case int32:
s = strconv.FormatInt(int64(x), 10)
case int64:
s = strconv.FormatInt(x, 10)
case float32:
s = strconv.FormatFloat(float64(x), 'f', -1, 32)
case float64:
s = strconv.FormatFloat(x, 'f', -1, 64)
case string:
s = v.(string)
}
return s
}
func foreach(v interface{}, f func(interface{})) {
a := reflect.ValueOf(v)
for i := 0; i < a.Len(); i++ {
f(a.Index(i).Elem().Interface())
}
}