ctxhttp.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. // +build go1.7
  5. // Package ctxhttp provides helper functions for performing context-aware HTTP requests.
  6. package ctxhttp // import "golang.org/x/net/context/ctxhttp"
  7. import (
  8. "io"
  9. "net/http"
  10. "net/url"
  11. "strings"
  12. "golang.org/x/net/context"
  13. )
  14. // Do sends an HTTP request with the provided http.Client and returns
  15. // an HTTP response.
  16. //
  17. // If the client is nil, http.DefaultClient is used.
  18. //
  19. // The provided ctx must be non-nil. If it is canceled or times out,
  20. // ctx.Err() will be returned.
  21. func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
  22. if client == nil {
  23. client = http.DefaultClient
  24. }
  25. return client.Do(req.WithContext(ctx))
  26. }
  27. // Get issues a GET request via the Do function.
  28. func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
  29. req, err := http.NewRequest("GET", url, nil)
  30. if err != nil {
  31. return nil, err
  32. }
  33. return Do(ctx, client, req)
  34. }
  35. // Head issues a HEAD request via the Do function.
  36. func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
  37. req, err := http.NewRequest("HEAD", url, nil)
  38. if err != nil {
  39. return nil, err
  40. }
  41. return Do(ctx, client, req)
  42. }
  43. // Post issues a POST request via the Do function.
  44. func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) {
  45. req, err := http.NewRequest("POST", url, body)
  46. if err != nil {
  47. return nil, err
  48. }
  49. req.Header.Set("Content-Type", bodyType)
  50. return Do(ctx, client, req)
  51. }
  52. // PostForm issues a POST request via the Do function.
  53. func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) {
  54. return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  55. }