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

81 lines
1.4 KiB
Go
Raw Normal View History

2020-01-02 05:39:52 +00:00
package httputil
import (
"io"
"net/http"
"github.com/diamondburned/arikawa/utils/json"
2020-01-02 05:39:52 +00:00
)
type RequestOption func(*http.Request) error
func JSONRequest(r *http.Request) error {
r.Header.Set("Content-Type", "application/json")
return nil
}
2020-01-19 02:27:30 +00:00
func MultipartRequest(r *http.Request) error {
r.Header.Set("Content-Type", "multipart/form-data")
return nil
}
2020-01-19 03:12:08 +00:00
func WithContentType(ctype string) RequestOption {
return func(r *http.Request) error {
r.Header.Set("Content-Type", ctype)
return nil
}
}
2020-01-06 03:48:39 +00:00
func WithSchema(schema SchemaEncoder, v interface{}) RequestOption {
2020-01-02 05:39:52 +00:00
return func(r *http.Request) error {
2020-01-06 03:48:39 +00:00
params, err := schema.Encode(v)
if err != nil {
return err
}
var qs = r.URL.Query()
for k, v := range params {
qs[k] = append(qs[k], v...)
}
r.URL.RawQuery = qs.Encode()
2020-01-02 05:39:52 +00:00
return nil
}
}
2020-01-06 03:48:39 +00:00
func WithBody(body io.ReadCloser) RequestOption {
return func(r *http.Request) error {
2020-01-19 02:27:30 +00:00
// tee := io.TeeReader(body, os.Stderr)
// r.Body = ioutil.NopCloser(tee)
2020-01-06 03:48:39 +00:00
r.Body = body
2020-01-19 02:27:30 +00:00
r.ContentLength = -1
2020-01-06 03:48:39 +00:00
return nil
}
}
2020-01-02 05:39:52 +00:00
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 {
return func(*http.Request) error {
return nil
}
}
var err error
var rp, wp = io.Pipe()
2020-01-02 05:39:52 +00:00
go func() {
err = json.EncodeStream(wp, v)
wp.Close()
2020-01-02 05:39:52 +00:00
}()
return func(r *http.Request) error {
if err != nil {
return err
}
2020-01-15 04:43:34 +00:00
r.Header.Set("Content-Type", "application/json")
r.Body = rp
2020-01-02 05:39:52 +00:00
return nil
}
}