ctxhttp.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. resp, err := client.Do(req.WithContext(ctx))
  26. // If we got an error, and the context has been canceled,
  27. // the context's error is probably more useful.
  28. if err != nil {
  29. select {
  30. case <-ctx.Done():
  31. err = ctx.Err()
  32. default:
  33. }
  34. }
  35. return resp, err
  36. }
  37. // Get issues a GET request via the Do function.
  38. func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
  39. req, err := http.NewRequest("GET", url, nil)
  40. if err != nil {
  41. return nil, err
  42. }
  43. return Do(ctx, client, req)
  44. }
  45. // Head issues a HEAD request via the Do function.
  46. func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
  47. req, err := http.NewRequest("HEAD", url, nil)
  48. if err != nil {
  49. return nil, err
  50. }
  51. return Do(ctx, client, req)
  52. }
  53. // Post issues a POST request via the Do function.
  54. func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) {
  55. req, err := http.NewRequest("POST", url, body)
  56. if err != nil {
  57. return nil, err
  58. }
  59. req.Header.Set("Content-Type", bodyType)
  60. return Do(ctx, client, req)
  61. }
  62. // PostForm issues a POST request via the Do function.
  63. func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) {
  64. return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  65. }