1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3 4 package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
5 6 import (
7 "context"
8 "io"
9 "net/http"
10 "net/url"
11 "strings"
12 )
13 14 // DefaultClient is the default Client and is used by Get, Head, Post and PostForm.
15 // Please be careful of initialization order - for example, if you change
16 // the global propagator, the DefaultClient might still be using the old one.
17 var DefaultClient = &http.Client{Transport: NewTransport(http.DefaultTransport)}
18 19 // Get is a convenient replacement for http.Get that adds a span around the request.
20 func Get(ctx context.Context, targetURL string) (resp *http.Response, err error) {
21 req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
22 if err != nil {
23 return nil, err
24 }
25 return DefaultClient.Do(req)
26 }
27 28 // Head is a convenient replacement for http.Head that adds a span around the request.
29 func Head(ctx context.Context, targetURL string) (resp *http.Response, err error) {
30 req, err := http.NewRequestWithContext(ctx, http.MethodHead, targetURL, nil)
31 if err != nil {
32 return nil, err
33 }
34 return DefaultClient.Do(req)
35 }
36 37 // Post is a convenient replacement for http.Post that adds a span around the request.
38 func Post(ctx context.Context, targetURL, contentType string, body io.Reader) (resp *http.Response, err error) {
39 req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, body)
40 if err != nil {
41 return nil, err
42 }
43 req.Header.Set("Content-Type", contentType)
44 return DefaultClient.Do(req)
45 }
46 47 // PostForm is a convenient replacement for http.PostForm that adds a span around the request.
48 func PostForm(ctx context.Context, targetURL string, data url.Values) (resp *http.Response, err error) {
49 return Post(ctx, targetURL, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
50 }
51