2020-01-02 05:39:52 +00:00
|
|
|
package httputil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
|
2020-04-09 02:28:40 +00:00
|
|
|
"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
|
2020-01-20 19:28:55 +00:00
|
|
|
var rp, wp = io.Pipe()
|
2020-01-02 05:39:52 +00:00
|
|
|
|
|
|
|
go func() {
|
2020-01-20 19:28:55 +00:00
|
|
|
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")
|
2020-01-20 19:28:55 +00:00
|
|
|
r.Body = rp
|
2020-01-02 05:39:52 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|