Skip to content

Commit

Permalink
Allow to overwrite User-Agent http request header (#335) (#336)
Browse files Browse the repository at this point in the history
  • Loading branch information
aleksmaus authored Aug 23, 2021
1 parent 009f141 commit 845c8ef
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
11 changes: 10 additions & 1 deletion estransport/estransport.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ const (

// esCompatHeader defines the env var for Compatibility header.
esCompatHeader = "ELASTIC_CLIENT_APIVERSIONING"

userAgentHeader = "User-Agent"
)

var (
Expand Down Expand Up @@ -474,7 +476,14 @@ func (c *Client) setReqAuth(u *url.URL, req *http.Request) *http.Request {
}

func (c *Client) setReqUserAgent(req *http.Request) *http.Request {
req.Header.Set("User-Agent", userAgent)
if len(c.header) > 0 {
ua := c.header.Get(userAgentHeader)
if ua != "" {
req.Header.Set(userAgentHeader, ua)
return req
}
}
req.Header.Set(userAgentHeader, userAgent)
return req
}

Expand Down
15 changes: 15 additions & 0 deletions estransport/estransport_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,21 @@ func TestTransportPerform(t *testing.T) {
}
})

t.Run("Overwrites UserAgent", func(t *testing.T) {
u, _ := url.Parse("http://example.com")

tp, _ := New(Config{URLs: []*url.URL{u}, Header: http.Header{
userAgentHeader: []string{"Elastic-Fleet-Server/7.11.1 (darwin; amd64; Go 1.16.6)"},
}})

req, _ := http.NewRequest("GET", "/abc", nil)
tp.setReqUserAgent(req)

if !strings.HasPrefix(req.UserAgent(), "Elastic-Fleet-Server") {
t.Errorf("Unexpected user agent: %s", req.UserAgent())
}
})

t.Run("Sets global HTTP request headers", func(t *testing.T) {
hdr := http.Header{}
hdr.Set("X-Foo", "bar")
Expand Down

0 comments on commit 845c8ef

Please sign in to comment.