-
Notifications
You must be signed in to change notification settings - Fork 1
/
encode.go
76 lines (62 loc) · 1.82 KB
/
encode.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
package patch
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
)
// Encoder is the interface for types that can encode a request body.
type Encoder interface {
ContentType() string
Encode(interface{}) (io.Reader, error)
}
// EncoderJSON encodes bodies as JSON
type EncoderJSON struct{
// CustomContentType overrides the default ContentType
// of application/json; charset=utf-8
CustomContentType string
}
// ContentType returns the ContentType header to set in an outbound request
func (e EncoderJSON) ContentType() string {
if e.CustomContentType != "" {
return e.CustomContentType
}
return "application/json; charset=utf-8"
}
// Encode marshals an arbitrary data structure into JSON
func (e EncoderJSON) Encode(body interface{}) (io.Reader, error) {
b, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("failed to encode body as JSON: %w", err)
}
return bytes.NewReader(b), nil
}
// EncoderFormURL encodes bodies as x-www-form-urlencoded
type EncoderFormURL struct {
// CustomContentType overrides the default ContentType
// of application/x-www-form-urlencoded
CustomContentType string
// TagAlias is the tag to read on struct fields.
// If empty, "form" will be used.
TagAlias string
}
// ContentType returns the ContentType header to set in an outbound request
func (e EncoderFormURL) ContentType() string {
if e.CustomContentType != "" {
return e.CustomContentType
}
return "application/x-www-form-urlencoded"
}
// Encode marshals maps and simple structs to a URL-encoded body
func (e EncoderFormURL) Encode(body interface{}) (io.Reader, error) {
tagAlias := "form"
if e.TagAlias != "" {
tagAlias = e.TagAlias
}
values, err := toQueryString(body, tagAlias)
if err != nil {
return nil, fmt.Errorf("failed to Encode body as URL query: %w", err)
}
return strings.NewReader(values), nil
}