1
0
Fork 0
mirror of https://github.com/diamondburned/arikawa.git synced 2024-11-08 16:04:41 +00:00
arikawa/utils/httputil/options.go

98 lines
1.9 KiB
Go
Raw Normal View History

2020-01-02 05:39:52 +00:00
package httputil
import (
"io"
"net/http"
2020-04-19 21:53:53 +00:00
"github.com/diamondburned/arikawa/utils/httputil/httpdriver"
"github.com/diamondburned/arikawa/utils/json"
2020-01-02 05:39:52 +00:00
)
2020-04-19 21:53:53 +00:00
type RequestOption func(httpdriver.Request) error
2020-05-03 21:02:03 +00:00
type ResponseFunc func(httpdriver.Request, httpdriver.Response) error
2020-01-02 05:39:52 +00:00
2020-04-19 21:53:53 +00:00
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"},
})
2020-01-02 05:39:52 +00:00
return nil
}
2020-04-19 21:53:53 +00:00
func MultipartRequest(r httpdriver.Request) error {
r.AddHeader(http.Header{
"Content-Type": {"multipart/form-data"},
})
2020-01-19 02:27:30 +00:00
return nil
}
2020-04-19 16:17:04 +00:00
func WithHeaders(headers http.Header) RequestOption {
2020-04-19 21:53:53 +00:00
return func(r httpdriver.Request) error {
r.AddHeader(headers)
2020-04-19 16:17:04 +00:00
return nil
}
}
2020-01-19 03:12:08 +00:00
func WithContentType(ctype string) RequestOption {
2020-04-19 21:53:53 +00:00
return func(r httpdriver.Request) error {
r.AddHeader(http.Header{
"Content-Type": {ctype},
})
2020-01-19 03:12:08 +00:00
return nil
}
}
2020-01-06 03:48:39 +00:00
func WithSchema(schema SchemaEncoder, v interface{}) RequestOption {
2020-04-19 21:53:53 +00:00
return func(r httpdriver.Request) error {
2020-01-06 03:48:39 +00:00
params, err := schema.Encode(v)
if err != nil {
return err
}
2020-04-19 21:53:53 +00:00
r.AddQuery(params)
2020-01-02 05:39:52 +00:00
return nil
}
}
2020-01-06 03:48:39 +00:00
func WithBody(body io.ReadCloser) RequestOption {
2020-04-19 21:53:53 +00:00
return func(r httpdriver.Request) error {
r.WithBody(body)
2020-01-06 03:48:39 +00:00
return nil
}
}
2020-01-02 05:39:52 +00:00
2020-04-19 21:53:53 +00:00
// WithJSONBody inserts a JSON body into the request. This ignores JSON errors.
2020-01-06 03:48:39 +00:00
func WithJSONBody(json json.Driver, v interface{}) RequestOption {
2020-01-02 05:39:52 +00:00
if v == nil {
2020-04-19 21:53:53 +00:00
return func(httpdriver.Request) error {
2020-01-02 05:39:52 +00:00
return nil
}
}
var rp, wp = io.Pipe()
2020-01-02 05:39:52 +00:00
go func() {
2020-04-19 21:53:53 +00:00
json.EncodeStream(wp, v)
wp.Close()
2020-01-02 05:39:52 +00:00
}()
2020-04-19 21:53:53 +00:00
return func(r httpdriver.Request) error {
// TODO: maybe do something to this?
// if err != nil {
// return err
// }
2020-01-02 05:39:52 +00:00
2020-04-19 21:53:53 +00:00
r.AddHeader(http.Header{
"Content-Type": {"application/json"},
})
r.WithBody(rp)
2020-01-02 05:39:52 +00:00
return nil
}
}