|
| 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 | + |
| 15 | +package otelhttp |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "io" |
| 20 | + "net/http" |
| 21 | + "net/url" |
| 22 | + "strings" |
| 23 | +) |
| 24 | + |
| 25 | +// DefaultClient is the default Client and is used by Get, Head, Post and PostForm. |
| 26 | +// Please be careful of intitialization order - for example, if you change |
| 27 | +// the global propagator, the DefaultClient might still be using the old one |
| 28 | +var DefaultClient = &http.Client{Transport: NewTransport(http.DefaultTransport)} |
| 29 | + |
| 30 | +// Get is a convenient replacement for http.Get that adds a span around the request. |
| 31 | +func Get(ctx context.Context, url string) (resp *http.Response, err error) { |
| 32 | + req, err := http.NewRequestWithContext(ctx, "GET", url, nil) |
| 33 | + if err != nil { |
| 34 | + return nil, err |
| 35 | + } |
| 36 | + return DefaultClient.Do(req) |
| 37 | +} |
| 38 | + |
| 39 | +// Head is a convenient replacement for http.Head that adds a span around the request. |
| 40 | +func Head(ctx context.Context, url string) (resp *http.Response, err error) { |
| 41 | + req, err := http.NewRequestWithContext(ctx, "HEAD", url, nil) |
| 42 | + if err != nil { |
| 43 | + return nil, err |
| 44 | + } |
| 45 | + return DefaultClient.Do(req) |
| 46 | +} |
| 47 | + |
| 48 | +// Post is a convenient replacement for http.Post that adds a span around the request. |
| 49 | +func Post(ctx context.Context, url, contentType string, body io.Reader) (resp *http.Response, err error) { |
| 50 | + req, err := http.NewRequestWithContext(ctx, "POST", url, body) |
| 51 | + if err != nil { |
| 52 | + return nil, err |
| 53 | + } |
| 54 | + req.Header.Set("Content-Type", contentType) |
| 55 | + return DefaultClient.Do(req) |
| 56 | +} |
| 57 | + |
| 58 | +// PostForm is a convenient replacement for http.PostForm that adds a span around the request. |
| 59 | +func PostForm(ctx context.Context, url string, data url.Values) (resp *http.Response, err error) { |
| 60 | + return Post(ctx, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) |
| 61 | +} |
0 commit comments