github.com/diamondburned/arikawa/v2@v2.1.0/utils/httputil/httpdriver/default.go (about) 1 package httpdriver 2 3 import ( 4 "context" 5 "io" 6 "net/http" 7 "net/url" 8 "time" 9 ) 10 11 // DefaultClient implements Client and wraps around the stdlib Client. 12 type DefaultClient http.Client 13 14 var _ Client = (*DefaultClient)(nil) 15 16 // WrapClient wraps around the standard library's http.Client and returns an 17 // implementation that's compatible with the Client driver interface. 18 func WrapClient(client http.Client) Client { 19 return DefaultClient(client) 20 } 21 22 // NewClient creates a new client around the standard library's http.Client. The 23 // client will have a timeout of 10 seconds. 24 func NewClient() Client { 25 return WrapClient(http.Client{ 26 Timeout: 10 * time.Second, 27 }) 28 } 29 30 func (d DefaultClient) NewRequest(ctx context.Context, method, url string) (Request, error) { 31 r, err := http.NewRequestWithContext(ctx, method, url, nil) 32 if err != nil { 33 return nil, err 34 } 35 return (*DefaultRequest)(r), nil 36 } 37 38 func (d DefaultClient) Do(req Request) (Response, error) { 39 // Implementations can safely assert this. 40 request := req.(*DefaultRequest) 41 42 r, err := (*http.Client)(&d).Do((*http.Request)(request)) 43 if err != nil { 44 return nil, err 45 } 46 47 return (*DefaultResponse)(r), nil 48 } 49 50 // DefaultRequest wraps around the stdlib Request and satisfies the Request 51 // interface. 52 type DefaultRequest http.Request 53 54 var _ Request = (*DefaultRequest)(nil) 55 56 func (r *DefaultRequest) GetPath() string { 57 return r.URL.Path 58 } 59 60 func (r *DefaultRequest) GetContext() context.Context { 61 return (*http.Request)(r).Context() 62 } 63 64 func (r *DefaultRequest) AddQuery(values url.Values) { 65 var qs = r.URL.Query() 66 for k, v := range values { 67 qs[k] = append(qs[k], v...) 68 } 69 70 r.URL.RawQuery = qs.Encode() 71 } 72 73 func (r *DefaultRequest) AddHeader(header http.Header) { 74 for key, values := range header { 75 r.Header[key] = append(r.Header[key], values...) 76 } 77 } 78 79 func (r *DefaultRequest) WithBody(body io.ReadCloser) { 80 r.Body = body 81 } 82 83 // DefaultResponse wraps around the stdlib Response and satisfies the Response 84 // interface. 85 type DefaultResponse http.Response 86 87 var _ Response = (*DefaultResponse)(nil) 88 89 func (r *DefaultResponse) GetStatus() int { 90 return r.StatusCode 91 } 92 93 func (r *DefaultResponse) GetHeader() http.Header { 94 return r.Header 95 } 96 97 func (r *DefaultResponse) GetBody() io.ReadCloser { 98 return r.Body 99 }