An http.RoundTripper which adds the HTTP User-Agent header to all requests

This code existed in cert-manager once before and I'm reviving it.
Here's the history:

 * Added:
 https://github.com/cert-manager/cert-manager/pull/422
 * Moved: https://github.com/cert-manager/cert-manager/pull/432
 * Obsoleted: https://github.com/cert-manager/cert-manager/pull/797
 * Deleted: https://github.com/cert-manager/cert-manager/pull/966

Signed-off-by: Richard Wall <richard.wall@venafi.com>
This commit is contained in:
Richard Wall 2024-03-20 10:24:47 +00:00
parent f56fc1ed1a
commit 112c7b2e9e

View File

@ -19,6 +19,7 @@ package util
import (
"bytes"
"fmt"
"net/http"
"strings"
"unicode"
"unicode/utf8"
@ -58,3 +59,25 @@ func PrefixFromUserAgent(u string) string {
}
return buf.String()
}
// UserAgentRoundTripper implements the http.RoundTripper interface and adds a User-Agent
// header.
type userAgentRoundTripper struct {
inner http.RoundTripper
userAgent string
}
// UserAgentRoundTripper returns a RoundTripper that functions identically to
// the provided 'inner' round tripper, other than also setting a user agent.
func UserAgentRoundTripper(inner http.RoundTripper, userAgent string) http.RoundTripper {
return userAgentRoundTripper{
inner: inner,
userAgent: userAgent,
}
}
// RoundTrip implements http.RoundTripper
func (u userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("User-Agent", u.userAgent)
return u.inner.RoundTrip(req)
}