-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathbody.go
77 lines (68 loc) · 1.73 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
package requests
import (
"bytes"
"io"
"net/url"
"os"
"strings"
)
// BodyGetter provides a Builder with a source for a request body.
type BodyGetter = func() (io.ReadCloser, error)
// BodyReader is a BodyGetter that returns an io.Reader.
func BodyReader(r io.Reader) BodyGetter {
return func() (io.ReadCloser, error) {
if rc, ok := r.(io.ReadCloser); ok {
return rc, nil
}
return rc(r), nil
}
}
// BodyWriter is a BodyGetter that pipes writes into a request body.
func BodyWriter(f func(w io.Writer) error) BodyGetter {
return func() (io.ReadCloser, error) {
r, w := io.Pipe()
go func() {
var err error
defer func() {
w.CloseWithError(err)
}()
err = f(w)
}()
return r, nil
}
}
// BodyBytes is a BodyGetter that returns the provided raw bytes.
func BodyBytes(b []byte) BodyGetter {
return func() (io.ReadCloser, error) {
return rc(bytes.NewReader(b)), nil
}
}
// BodySerializer is a BodyGetter
// that uses the provided [Serializer]
// to build the body of a request from v.
func BodySerializer(s Serializer, v any) BodyGetter {
return func() (io.ReadCloser, error) {
b, err := s(v)
if err != nil {
return nil, err
}
return rc(bytes.NewReader(b)), nil
}
}
// BodyJSON is a [BodySerializer]
// that uses [JSONSerializer] to marshal the object.
func BodyJSON(v any) BodyGetter {
return BodySerializer(JSONSerializer, v)
}
// BodyForm is a BodyGetter that builds an encoded form body.
func BodyForm(data url.Values) BodyGetter {
return func() (r io.ReadCloser, err error) {
return rc(strings.NewReader(data.Encode())), nil
}
}
// BodyFile is a BodyGetter that reads the provided file path.
func BodyFile(name string) BodyGetter {
return func() (r io.ReadCloser, err error) {
return os.Open(name)
}
}