forked from diamondburned/arikawa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
options.go
94 lines (79 loc) · 1.88 KB
/
options.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
package httputil
import (
"io"
"net/http"
"net/url"
"github.com/zBNF/arikawa/v3/utils/httputil/httpdriver"
"github.com/zBNF/arikawa/v3/utils/json"
)
type RequestOption func(httpdriver.Request) error
type ResponseFunc func(httpdriver.Request, httpdriver.Response) error
func PrependOptions(opts []RequestOption, prepend ...RequestOption) []RequestOption {
if len(opts) == 0 {
return prepend
}
return append(prepend, opts...)
}
func JSONRequest(r httpdriver.Request) error {
r.AddHeader(http.Header{
"Content-Type": {"application/json"},
})
return nil
}
func MultipartRequest(r httpdriver.Request) error {
r.AddHeader(http.Header{
"Content-Type": {"multipart/form-data"},
})
return nil
}
func WithHeaders(headers http.Header) RequestOption {
return func(r httpdriver.Request) error {
r.AddHeader(headers)
return nil
}
}
func WithContentType(ctype string) RequestOption {
return func(r httpdriver.Request) error {
r.AddHeader(http.Header{
"Content-Type": {ctype},
})
return nil
}
}
func WithSchema(schema SchemaEncoder, v interface{}) RequestOption {
return func(r httpdriver.Request) error {
var params url.Values
if p, ok := v.(url.Values); ok {
params = p
} else {
p, err := schema.Encode(v)
if err != nil {
return err
}
params = p
}
r.AddQuery(params)
return nil
}
}
func WithBody(body io.ReadCloser) RequestOption {
return func(r httpdriver.Request) error {
r.WithBody(body)
return nil
}
}
// WithJSONBody inserts a JSON body into the request. This ignores JSON errors.
func WithJSONBody(v interface{}) RequestOption {
if v == nil {
return func(httpdriver.Request) error { return nil }
}
return func(r httpdriver.Request) error {
rp, wp := io.Pipe()
go func() { wp.CloseWithError(json.EncodeStream(wp, v)) }()
r.AddHeader(http.Header{
"Content-Type": {"application/json"},
})
r.WithBody(rp)
return nil
}
}