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// +build go1.7
6
7// Package ctxhttp provides helper functions for performing context-aware HTTP requests.
8package ctxhttp
9
10import (
11	"io"
12	"net/http"
13	"net/url"
14	"strings"
15
16	"golang.org/x/net/context"
17)
18
19// Do sends an HTTP request with the provided http.Client and returns
20// an HTTP response.
21//
22// If the client is nil, http.DefaultClient is used.
23//
24// The provided ctx must be non-nil. If it is canceled or times out,
25// ctx.Err() will be returned.
26func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
27	if client == nil {
28		client = http.DefaultClient
29	}
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.
33	if err != nil {
34		select {
35		case <-ctx.Done():
36			err = ctx.Err()
37		default:
38		}
39	}
40	return resp, err
41}
42
43// Get issues a GET request via the Do function.
44func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
45	req, err := http.NewRequest("GET", url, nil)
46	if err != nil {
47		return nil, err
48	}
49	return Do(ctx, client, req)
50}
51
52// Head issues a HEAD request via the Do function.
53func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
54	req, err := http.NewRequest("HEAD", url, nil)
55	if err != nil {
56		return nil, err
57	}
58	return Do(ctx, client, req)
59}
60
61// Post issues a POST request via the Do function.
62func 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)
64	if err != nil {
65		return nil, err
66	}
67	req.Header.Set("Content-Type", bodyType)
68	return Do(ctx, client, req)
69}
70
71// PostForm issues a POST request via the Do function.
72func 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()))
74}
75