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.
7 // Package ctxhttp provides helper functions for performing context-aware HTTP requests.
8 package ctxhttp // import "golang.org/x/net/context/ctxhttp"
16 "golang.org/x/net/context"
19 // Do sends an HTTP request with the provided http.Client and returns
22 // If the client is nil, http.DefaultClient is used.
24 // The provided ctx must be non-nil. If it is canceled or times out,
25 // ctx.Err() will be returned.
26 func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
28 client = http.DefaultClient
30 resp, err := client.Do(req.WithContext(ctx))
31 // If we got an error, and the context has been canceled,
32 // the context's error is probably more useful.
43 // Get issues a GET request via the Do function.
44 func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
45 req, err := http.NewRequest("GET", url, nil)
49 return Do(ctx, client, req)
52 // Head issues a HEAD request via the Do function.
53 func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
54 req, err := http.NewRequest("HEAD", url, nil)
58 return Do(ctx, client, req)
61 // Post issues a POST request via the Do function.
62 func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) {
63 req, err := http.NewRequest("POST", url, body)
67 req.Header.Set("Content-Type", bodyType)
68 return Do(ctx, client, req)
71 // PostForm issues a POST request via the Do function.
72 func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) {
73 return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))