client.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright The OpenTelemetry Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
  15. import (
  16. "context"
  17. "io"
  18. "net/http"
  19. "net/url"
  20. "strings"
  21. )
  22. // DefaultClient is the default Client and is used by Get, Head, Post and PostForm.
  23. // Please be careful of intitialization order - for example, if you change
  24. // the global propagator, the DefaultClient might still be using the old one.
  25. var DefaultClient = &http.Client{Transport: NewTransport(http.DefaultTransport)}
  26. // Get is a convenient replacement for http.Get that adds a span around the request.
  27. func Get(ctx context.Context, targetURL string) (resp *http.Response, err error) {
  28. req, err := http.NewRequestWithContext(ctx, "GET", targetURL, nil)
  29. if err != nil {
  30. return nil, err
  31. }
  32. return DefaultClient.Do(req)
  33. }
  34. // Head is a convenient replacement for http.Head that adds a span around the request.
  35. func Head(ctx context.Context, targetURL string) (resp *http.Response, err error) {
  36. req, err := http.NewRequestWithContext(ctx, "HEAD", targetURL, nil)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return DefaultClient.Do(req)
  41. }
  42. // Post is a convenient replacement for http.Post that adds a span around the request.
  43. func Post(ctx context.Context, targetURL, contentType string, body io.Reader) (resp *http.Response, err error) {
  44. req, err := http.NewRequestWithContext(ctx, "POST", targetURL, body)
  45. if err != nil {
  46. return nil, err
  47. }
  48. req.Header.Set("Content-Type", contentType)
  49. return DefaultClient.Do(req)
  50. }
  51. // PostForm is a convenient replacement for http.PostForm that adds a span around the request.
  52. func PostForm(ctx context.Context, targetURL string, data url.Values) (resp *http.Response, err error) {
  53. return Post(ctx, targetURL, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  54. }