http: allow custom User-Agent for outgoing HTTP requests

This commit is contained in:
Srigovind Nayak
2024-05-27 03:33:11 +05:30
committed by Michael Eischer
parent cdd210185d
commit de7b418bbe
6 changed files with 100 additions and 0 deletions

View File

@@ -28,6 +28,9 @@ type TransportOptions struct {
// Skip TLS certificate verification
InsecureTLS bool
// Specify Custom User-Agent for the http Client
HTTPUserAgent string
}
// readPEMCertKey reads a file and returns the PEM encoded certificate and key
@@ -132,6 +135,13 @@ func Transport(opts TransportOptions) (http.RoundTripper, error) {
}
rt := http.RoundTripper(tr)
// if the userAgent is set in the Transport Options, wrap the
// http.RoundTripper
if opts.HTTPUserAgent != "" {
rt = newCustomUserAgentRoundTripper(rt, opts.HTTPUserAgent)
}
if feature.Flag.Enabled(feature.BackendErrorRedesign) {
rt = newWatchdogRoundtripper(rt, 120*time.Second, 128*1024)
}

View File

@@ -0,0 +1,25 @@
package backend
import "net/http"
// httpUserAgentRoundTripper is a custom http.RoundTripper that modifies the User-Agent header
// of outgoing HTTP requests.
type httpUserAgentRoundTripper struct {
userAgent string
rt http.RoundTripper
}
func newCustomUserAgentRoundTripper(rt http.RoundTripper, userAgent string) *httpUserAgentRoundTripper {
return &httpUserAgentRoundTripper{
rt: rt,
userAgent: userAgent,
}
}
// RoundTrip modifies the User-Agent header of the request and then delegates the request
// to the underlying RoundTripper.
func (c *httpUserAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
req = req.Clone(req.Context())
req.Header.Set("User-Agent", c.userAgent)
return c.rt.RoundTrip(req)
}

View File

@@ -0,0 +1,50 @@
package backend
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestCustomUserAgentTransport(t *testing.T) {
// Create a mock HTTP handler that checks the User-Agent header
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userAgent := r.Header.Get("User-Agent")
if userAgent != "TestUserAgent" {
t.Errorf("Expected User-Agent: TestUserAgent, got: %s", userAgent)
}
w.WriteHeader(http.StatusOK)
})
// Create a test server with the mock handler
server := httptest.NewServer(handler)
defer server.Close()
// Create a custom user agent transport
customUserAgent := "TestUserAgent"
transport := &httpUserAgentRoundTripper{
userAgent: customUserAgent,
rt: http.DefaultTransport,
}
// Create an HTTP client with the custom transport
client := &http.Client{
Transport: transport,
}
// Make a request to the test server
resp, err := client.Get(server.URL)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
t.Log("failed to close response body")
}
}()
// Check the response status code
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status code: %d, got: %d", http.StatusOK, resp.StatusCode)
}
}