-
Notifications
You must be signed in to change notification settings - Fork 0
/
req_body.go
85 lines (70 loc) · 1.75 KB
/
req_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
package greq
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/url"
"strings"
"github.com/gookit/goutil/netutil/httpctype"
)
// BodyProvider provides Body content for http.Request attachment.
type BodyProvider interface {
// ContentType returns the Content-Type of the body.
ContentType() string
// Body returns the io.Reader body.
Body() (io.Reader, error)
}
// bodyProvider provides the wrapped body value as a Body for reqests.
type bodyProvider struct {
body io.Reader
}
// ContentType value
func (p bodyProvider) ContentType() string {
return ""
}
// Body get body reader
func (p bodyProvider) Body() (io.Reader, error) {
return p.body, nil
}
// jsonBodyProvider encodes a JSON tagged struct value as a Body for requests.
type jsonBodyProvider struct {
payload any
}
// ContentType value
func (p jsonBodyProvider) ContentType() string {
return httpctype.JSON
}
// Body get body reader
func (p jsonBodyProvider) Body() (io.Reader, error) {
buf := &bytes.Buffer{}
err := json.NewEncoder(buf).Encode(p.payload)
if err != nil {
return nil, err
}
return buf, nil
}
// formBodyProvider encodes a url tagged struct value as Body for requests.
type formBodyProvider struct {
// allow type: string, url.Values
payload any
}
// ContentType value
func (p formBodyProvider) ContentType() string {
return httpctype.Form
}
// Body get body reader
func (p formBodyProvider) Body() (io.Reader, error) {
values, ok := p.payload.(url.Values)
if ok {
return strings.NewReader(values.Encode()), nil
}
mps, ok := p.payload.(map[string][]string)
if ok {
return strings.NewReader(url.Values(mps).Encode()), nil
}
if str, ok := p.payload.(string); ok {
return strings.NewReader(str), nil
}
return nil, errors.New("invalid payload data for Form body")
}