From c414f4de574257250c3ccb4281cc01e81354ce80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan-Otto=20Kr=C3=B6pke?= Date: Mon, 3 Jun 2024 19:16:46 +0200 Subject: [PATCH] Expose Host property in HTTPClientConfig --- config/http_config.go | 5 +++++ config/http_config_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/config/http_config.go b/config/http_config.go index 75e38bb8..ac6ffca5 100644 --- a/config/http_config.go +++ b/config/http_config.go @@ -319,6 +319,9 @@ type HTTPClientConfig struct { // The omitempty flag is not set, because it would be hidden from the // marshalled configuration when set to false. EnableHTTP2 bool `yaml:"enable_http2" json:"enable_http2"` + // HTTPHost optionally overrides the Host header to send. + // If empty, the host from the URL is used. + HTTPHost string `yaml:"http_host,omitempty" json:"host,omitempty"` // Proxy configuration. ProxyConfig `yaml:",inline"` // HTTPHeaders specify headers to inject in the requests. Those headers @@ -664,6 +667,8 @@ func NewRoundTripperFromConfigWithContext(ctx context.Context, cfg HTTPClientCon if opts.host != "" { rt = NewHostRoundTripper(opts.host, rt) + } else if cfg.HTTPHost != "" { + rt = NewHostRoundTripper(cfg.HTTPHost, rt) } // Return a new configured RoundTripper. diff --git a/config/http_config_test.go b/config/http_config_test.go index 14e07c22..a39d3e93 100644 --- a/config/http_config_test.go +++ b/config/http_config_test.go @@ -1745,6 +1745,33 @@ func TestHost(t *testing.T) { })) defer ts.Close() + config := DefaultHTTPClientConfig + config.HTTPHost = "localhost.localdomain" + + rt, err := NewRoundTripperFromConfig(config, "test_host") + if err != nil { + t.Fatal(err) + } + + client := http.Client{ + Transport: rt, + } + _, err = client.Get(ts.URL) + if err != nil { + t.Fatal(err) + } +} + +func TestHostWithNewRoundTripperFromConfig(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Host != "localhost.localdomain" { + t.Fatalf("Expected Host header in request to be 'localhost.localdomain', got '%s'", r.Host) + } + + w.Header().Add("Content-Type", "application/json") + })) + defer ts.Close() + config := DefaultHTTPClientConfig rt, err := NewRoundTripperFromConfig(config, "test_host", WithHost("localhost.localdomain"))