From 112c7b2e9e4107a7715ac465e58dd4eecfd6bd97 Mon Sep 17 00:00:00 2001 From: Richard Wall Date: Wed, 20 Mar 2024 10:24:47 +0000 Subject: [PATCH] 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 --- pkg/util/useragent.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/pkg/util/useragent.go b/pkg/util/useragent.go index 34a5a757b..7372031a1 100644 --- a/pkg/util/useragent.go +++ b/pkg/util/useragent.go @@ -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) +}