github.com/diamondburned/arikawa/v2@v2.1.0/utils/httputil/options.go (about) 1 package httputil 2 3 import ( 4 "io" 5 "net/http" 6 "net/url" 7 8 "github.com/diamondburned/arikawa/v2/utils/httputil/httpdriver" 9 "github.com/diamondburned/arikawa/v2/utils/json" 10 ) 11 12 type RequestOption func(httpdriver.Request) error 13 type ResponseFunc func(httpdriver.Request, httpdriver.Response) error 14 15 func PrependOptions(opts []RequestOption, prepend ...RequestOption) []RequestOption { 16 if len(opts) == 0 { 17 return prepend 18 } 19 return append(prepend, opts...) 20 } 21 22 func JSONRequest(r httpdriver.Request) error { 23 r.AddHeader(http.Header{ 24 "Content-Type": {"application/json"}, 25 }) 26 return nil 27 } 28 29 func MultipartRequest(r httpdriver.Request) error { 30 r.AddHeader(http.Header{ 31 "Content-Type": {"multipart/form-data"}, 32 }) 33 return nil 34 } 35 36 func WithHeaders(headers http.Header) RequestOption { 37 return func(r httpdriver.Request) error { 38 r.AddHeader(headers) 39 return nil 40 } 41 } 42 43 func WithContentType(ctype string) RequestOption { 44 return func(r httpdriver.Request) error { 45 r.AddHeader(http.Header{ 46 "Content-Type": {ctype}, 47 }) 48 return nil 49 } 50 } 51 52 func WithSchema(schema SchemaEncoder, v interface{}) RequestOption { 53 return func(r httpdriver.Request) error { 54 var params url.Values 55 56 if p, ok := v.(url.Values); ok { 57 params = p 58 } else { 59 p, err := schema.Encode(v) 60 if err != nil { 61 return err 62 } 63 params = p 64 } 65 66 r.AddQuery(params) 67 return nil 68 } 69 } 70 71 func WithBody(body io.ReadCloser) RequestOption { 72 return func(r httpdriver.Request) error { 73 r.WithBody(body) 74 return nil 75 } 76 } 77 78 // WithJSONBody inserts a JSON body into the request. This ignores JSON errors. 79 func WithJSONBody(v interface{}) RequestOption { 80 if v == nil { 81 return func(httpdriver.Request) error { return nil } 82 } 83 84 return func(r httpdriver.Request) error { 85 rp, wp := io.Pipe() 86 go func() { wp.CloseWithError(json.EncodeStream(wp, v)) }() 87 88 r.AddHeader(http.Header{ 89 "Content-Type": {"application/json"}, 90 }) 91 r.WithBody(rp) 92 return nil 93 } 94 }