2022-04-03 04:07:16 +00:00
|
|
|
package httpclient
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/hashicorp/go-cleanhttp"
|
2023-03-20 20:25:53 +00:00
|
|
|
"github.com/hashicorp/hc-install/version"
|
2022-04-03 04:07:16 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// NewHTTPClient provides a pre-configured http.Client
|
|
|
|
// e.g. with relevant User-Agent header
|
|
|
|
func NewHTTPClient() *http.Client {
|
|
|
|
client := cleanhttp.DefaultClient()
|
|
|
|
|
2023-03-20 20:25:53 +00:00
|
|
|
userAgent := fmt.Sprintf("hc-install/%s", version.Version())
|
2022-04-03 04:07:16 +00:00
|
|
|
|
|
|
|
cli := cleanhttp.DefaultPooledClient()
|
|
|
|
cli.Transport = &userAgentRoundTripper{
|
|
|
|
userAgent: userAgent,
|
|
|
|
inner: cli.Transport,
|
|
|
|
}
|
|
|
|
|
|
|
|
return client
|
|
|
|
}
|
|
|
|
|
|
|
|
type userAgentRoundTripper struct {
|
|
|
|
inner http.RoundTripper
|
|
|
|
userAgent string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rt *userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
|
|
if _, ok := req.Header["User-Agent"]; !ok {
|
|
|
|
req.Header.Set("User-Agent", rt.userAgent)
|
|
|
|
}
|
|
|
|
return rt.inner.RoundTrip(req)
|
|
|
|
}
|