-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathcore_req.go
106 lines (90 loc) · 2.33 KB
/
core_req.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
package requests
import (
"cmp"
"context"
"io"
"net/http"
"net/url"
"slices"
"github.com/carlmjohnson/requests/internal/minitrue"
)
// nopCloser is like io.NopCloser(),
// but it is a concrete type so we can strip it out
// before setting a body on a request.
// See https://github.com/carlmjohnson/requests/discussions/49
type nopCloser struct {
io.Reader
}
func rc(r io.Reader) nopCloser {
return nopCloser{r}
}
func (nopCloser) Close() error { return nil }
var _ io.ReadCloser = nopCloser{}
type requestBuilder struct {
headers []multimap
cookies []kvpair
getBody BodyGetter
method string
}
func (rb *requestBuilder) Header(key string, values ...string) {
rb.headers = append(rb.headers, multimap{key, values, false})
}
func (rb *requestBuilder) HeaderOptional(key string, values ...string) {
rb.headers = append(rb.headers, multimap{key, values, true})
}
func (rb *requestBuilder) Cookie(name, value string) {
rb.cookies = append(rb.cookies, kvpair{name, value})
}
func (rb *requestBuilder) Method(method string) {
rb.method = method
}
func (rb *requestBuilder) Body(src BodyGetter) {
rb.getBody = src
}
// Clone creates a new Builder suitable for independent mutation.
func (rb *requestBuilder) Clone() *requestBuilder {
rb2 := *rb
rb2.headers = slices.Clip(rb2.headers)
rb2.cookies = slices.Clip(rb2.cookies)
return &rb2
}
// Request builds a new http.Request with its context set.
func (rb *requestBuilder) Request(ctx context.Context, u *url.URL) (req *http.Request, err error) {
var body io.Reader
if rb.getBody != nil {
if body, err = rb.getBody(); err != nil {
return nil, err
}
if nopper, ok := body.(nopCloser); ok {
body = nopper.Reader
}
}
method := cmp.Or(rb.method,
minitrue.Cond(rb.getBody == nil,
http.MethodGet,
http.MethodPost))
req, err = http.NewRequestWithContext(ctx, method, u.String(), body)
if err != nil {
return nil, err
}
req.GetBody = rb.getBody
for _, kv := range rb.headers {
if !kv.optional {
req.Header[http.CanonicalHeaderKey(kv.key)] = kv.values
}
}
for _, kv := range rb.headers {
if kv.optional &&
req.Header.Get(kv.key) == "" &&
cmp.Or(kv.values...) != "" {
req.Header[http.CanonicalHeaderKey(kv.key)] = kv.values
}
}
for _, kv := range rb.cookies {
req.AddCookie(&http.Cookie{
Name: kv.key,
Value: kv.value,
})
}
return req, nil
}