1
0
Fork 0
mirror of https://github.com/diamondburned/arikawa.git synced 2024-11-17 20:32:48 +00:00
arikawa/httputil/options.go

66 lines
1 KiB
Go
Raw Normal View History

2020-01-02 05:39:52 +00:00
package httputil
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"github.com/diamondburned/arikawa/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-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 {
r.Body = body
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 buf bytes.Buffer
var err error
go func() {
err = json.EncodeStream(&buf, v)
}()
return func(r *http.Request) error {
if err != nil {
return err
}
r.Body = ioutil.NopCloser(&buf)
return nil
}
}