-
Notifications
You must be signed in to change notification settings - Fork 0
/
payload.go
102 lines (88 loc) · 2.09 KB
/
payload.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
package hhttp
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"strings"
)
type Payload interface {
Serialize() io.Reader
ContentType() string
}
type jsonPayload struct {
Payload string
}
func (p *jsonPayload) Serialize() io.Reader {
return strings.NewReader(p.Payload)
}
func (p *jsonPayload) ContentType() string {
return SerializationTypeJSON
}
// NewJSONPayload 会根据序列化类型,生成一个payload
// Content-Type = application/json
func NewJSONPayload(data interface{}) *jsonPayload {
p := jsonPayload{}
switch data.(type) {
case string, []byte:
p.Payload = fmt.Sprint(data)
default:
if b, err := json.Marshal(data); err != nil {
return nil
} else {
p.Payload = string(b)
}
}
return &p
}
type formPayload struct {
Payload map[string]string
}
func (p *formPayload) Serialize() io.Reader {
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
for k, v := range p.Payload {
_ = writer.WriteField(k, v)
}
if err := writer.Close(); err != nil {
return nil
}
return payload
}
// ContentType multipart/form-data 可能会存在一些问题,尽量避免使用。
func (p *formPayload) ContentType() string {
return SerializationTypeFormData
}
// NewFormPayload 会根据序列化类型,生成一个payload
// Content-Type = multipart/form-data
func NewFormPayload(data map[string]interface{}) *formPayload {
p := formPayload{
Payload: map[string]string{},
}
for k, v := range data {
p.Payload[k] = fmt.Sprint(v)
}
return &p
}
type wwwFormPayload struct {
Payload []string
}
func (p *wwwFormPayload) Serialize() io.Reader {
payload := strings.NewReader(strings.Join(p.Payload, "&"))
return payload
}
func (p *wwwFormPayload) ContentType() string {
return SerializationTypeWWWFrom
}
// NewWWWFormPayload 会根据序列化类型,生成一个payload
// Content-Type = application/x-www-form-urlencoded
func NewWWWFormPayload(data map[string]interface{}) *wwwFormPayload {
p := wwwFormPayload{
Payload: []string{},
}
for k, v := range data {
p.Payload = append(p.Payload, fmt.Sprintf("%s=%s", k, fmt.Sprint(v)))
}
return &p
}