ctxhttp.go 2.1 KB

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