arikawa/internal/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"
2020-01-15 18:32:54 +00:00
"github.com/diamondburned/arikawa/internal/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
}
}