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.
5 // Package ctxhttp provides helper functions for performing context-aware HTTP requests.
6 package ctxhttp // import "golang.org/x/net/context/ctxhttp"
16 // Do sends an HTTP request with the provided http.Client and returns
19 // If the client is nil, http.DefaultClient is used.
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) {
25 client = http.DefaultClient
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.
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)
46 return Do(ctx, client, req)
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)
55 return Do(ctx, client, req)
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)
64 req.Header.Set("Content-Type", bodyType)
65 return Do(ctx, client, req)
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()))