-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbody.go
118 lines (87 loc) · 2.09 KB
/
body.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
package room
import (
"bytes"
"encoding/json"
"github.com/google/go-querystring/query"
"mime/multipart"
"net/url"
)
type IBodyParser interface {
Parse() *bytes.Buffer
ContentType() string
}
type JsonBody struct {
v any
}
func (f *JsonBody) Parse() *bytes.Buffer {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(f.v)
if err != nil {
panic(err)
}
return &buf
}
func (f *JsonBody) ContentType() string {
return "application/json"
}
func NewJsonBodyParser(v any) IBodyParser {
return &JsonBody{v}
}
func NewFormURLEncodedBodyParser(v any) IBodyParser {
return &FormURLEncodedBody{v}
}
type FormURLEncodedBody struct {
v any
}
func (f *FormURLEncodedBody) ContentType() string {
return "application/x-www-form-urlencoded"
}
func (f *FormURLEncodedBody) Parse() *bytes.Buffer {
values := url.Values{}
switch f.v.(type) {
case map[string]any:
for key, value := range f.v.(map[string]any) {
values.Add(key, value.(string))
}
default:
values, _ = query.Values(f.v)
}
return bytes.NewBufferString(values.Encode())
}
// MultipartFormDataBody handles multipart/form-data encoding
type MultipartFormDataBody struct {
formData map[string]string
contentType string
}
func (f *MultipartFormDataBody) ContentType() string {
return f.contentType
}
func (f *MultipartFormDataBody) Parse() *bytes.Buffer {
var body bytes.Buffer
writer := multipart.NewWriter(&body)
for key, value := range f.formData {
_ = writer.WriteField(key, value)
}
//TODO cover file fields
_ = writer.Close()
f.contentType = writer.FormDataContentType()
return &body
}
func NewMultipartFormDataBodyParser(v any) IBodyParser {
formData := make(map[string]string)
if _, ok := v.(map[string]any); ok {
newMap := make(map[string]string)
for key, value := range v.(map[string]any) {
newMap[key] = value.(string)
}
formData = newMap
} else {
formData, _ = v.(map[string]string)
}
return &MultipartFormDataBody{
formData: formData,
}
}
type dumpBody struct{}
func (f dumpBody) Parse() *bytes.Buffer { return new(bytes.Buffer) }
func (f dumpBody) ContentType() string { return "" }