2023-09-07 19:55:58 -04:00
|
|
|
// Copyright The OpenTelemetry Authors
|
2024-11-01 09:10:09 -04:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
2023-09-07 19:55:58 -04:00
|
|
|
|
2023-10-13 15:38:21 -04:00
|
|
|
package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
2023-09-07 19:55:58 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// DefaultClient is the default Client and is used by Get, Head, Post and PostForm.
|
2024-11-01 09:10:09 -04:00
|
|
|
// Please be careful of initialization order - for example, if you change
|
2023-10-13 15:38:21 -04:00
|
|
|
// the global propagator, the DefaultClient might still be using the old one.
|
2023-09-07 19:55:58 -04:00
|
|
|
var DefaultClient = &http.Client{Transport: NewTransport(http.DefaultTransport)}
|
|
|
|
|
|
|
|
// Get is a convenient replacement for http.Get that adds a span around the request.
|
2023-10-13 15:38:21 -04:00
|
|
|
func Get(ctx context.Context, targetURL string) (resp *http.Response, err error) {
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "GET", targetURL, nil)
|
2023-09-07 19:55:58 -04:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return DefaultClient.Do(req)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Head is a convenient replacement for http.Head that adds a span around the request.
|
2023-10-13 15:38:21 -04:00
|
|
|
func Head(ctx context.Context, targetURL string) (resp *http.Response, err error) {
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "HEAD", targetURL, nil)
|
2023-09-07 19:55:58 -04:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return DefaultClient.Do(req)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Post is a convenient replacement for http.Post that adds a span around the request.
|
2023-10-13 15:38:21 -04:00
|
|
|
func Post(ctx context.Context, targetURL, contentType string, body io.Reader) (resp *http.Response, err error) {
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "POST", targetURL, body)
|
2023-09-07 19:55:58 -04:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
req.Header.Set("Content-Type", contentType)
|
|
|
|
return DefaultClient.Do(req)
|
|
|
|
}
|
|
|
|
|
|
|
|
// PostForm is a convenient replacement for http.PostForm that adds a span around the request.
|
2023-10-13 15:38:21 -04:00
|
|
|
func PostForm(ctx context.Context, targetURL string, data url.Values) (resp *http.Response, err error) {
|
|
|
|
return Post(ctx, targetURL, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
|
2023-09-07 19:55:58 -04:00
|
|
|
}
|