Zack Williams | e940c7a | 2019-08-21 14:25:39 -0700 | [diff] [blame] | 1 | // Copyright 2016 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package ctxhttp provides helper functions for performing context-aware HTTP requests. |
| 6 | package ctxhttp // import "golang.org/x/net/context/ctxhttp" |
| 7 | |
| 8 | import ( |
| 9 | "context" |
| 10 | "io" |
| 11 | "net/http" |
| 12 | "net/url" |
| 13 | "strings" |
| 14 | ) |
| 15 | |
| 16 | // Do sends an HTTP request with the provided http.Client and returns |
| 17 | // an HTTP response. |
| 18 | // |
| 19 | // If the client is nil, http.DefaultClient is used. |
| 20 | // |
| 21 | // The provided ctx must be non-nil. If it is canceled or times out, |
| 22 | // ctx.Err() will be returned. |
| 23 | func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { |
| 24 | if client == nil { |
| 25 | client = http.DefaultClient |
| 26 | } |
| 27 | resp, err := client.Do(req.WithContext(ctx)) |
| 28 | // If we got an error, and the context has been canceled, |
| 29 | // the context's error is probably more useful. |
| 30 | if err != nil { |
| 31 | select { |
| 32 | case <-ctx.Done(): |
| 33 | err = ctx.Err() |
| 34 | default: |
| 35 | } |
| 36 | } |
| 37 | return resp, err |
| 38 | } |
| 39 | |
| 40 | // Get issues a GET request via the Do function. |
| 41 | func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { |
| 42 | req, err := http.NewRequest("GET", url, nil) |
| 43 | if err != nil { |
| 44 | return nil, err |
| 45 | } |
| 46 | return Do(ctx, client, req) |
| 47 | } |
| 48 | |
| 49 | // Head issues a HEAD request via the Do function. |
| 50 | func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { |
| 51 | req, err := http.NewRequest("HEAD", url, nil) |
| 52 | if err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | return Do(ctx, client, req) |
| 56 | } |
| 57 | |
| 58 | // Post issues a POST request via the Do function. |
| 59 | func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { |
| 60 | req, err := http.NewRequest("POST", url, body) |
| 61 | if err != nil { |
| 62 | return nil, err |
| 63 | } |
| 64 | req.Header.Set("Content-Type", bodyType) |
| 65 | return Do(ctx, client, req) |
| 66 | } |
| 67 | |
| 68 | // PostForm issues a POST request via the Do function. |
| 69 | func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { |
| 70 | return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) |
| 71 | } |