Skip to content

Commit da05afb

Browse files
committed
Add "User-Agent" header to request in Perform()
In order to better identify/debug requests with the client, set the `User-Agent` header in the Perform() method of the transport.
1 parent 639e21a commit da05afb

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

elasticsearch_internal_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ func TestClientInterface(t *testing.T) {
108108
t.Errorf("Unexpected call to transport by client")
109109
}
110110

111-
c.Perform(&http.Request{URL: &url.URL{}}) // errcheck ignore
111+
c.Perform(&http.Request{URL: &url.URL{}, Header: make(http.Header)}) // errcheck ignore
112112

113113
if called != true { // megacheck ignore
114114
t.Errorf("Expected client to call transport")

estransport/estransport.go

+12
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,12 @@ import (
99
"github.com/elastic/go-elasticsearch/esapi"
1010
)
1111

12+
var userAgent string
13+
14+
func init() {
15+
userAgent = strings.Join([]string{"go-elasticsearch", Version}, "/")
16+
}
17+
1218
// Version returns the package version as a string.
1319
//
1420
const Version = esapi.Version
@@ -70,6 +76,7 @@ func (c *Client) Perform(req *http.Request) (*http.Response, error) {
7076

7177
c.setURL(u, req)
7278
c.setBasicAuth(u, req)
79+
c.setUserAgent(req)
7380

7481
// TODO(karmi): Wrap error
7582
return c.transport.RoundTrip(req)
@@ -114,3 +121,8 @@ func (c *Client) setBasicAuth(u *url.URL, req *http.Request) *http.Request {
114121

115122
return req
116123
}
124+
125+
func (c *Client) setUserAgent(req *http.Request) *http.Request {
126+
req.Header.Set("User-Agent", userAgent)
127+
return req
128+
}

estransport/estransport_internal_test.go

+13
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77
"net/http"
88
"net/url"
9+
"strings"
910
"testing"
1011
)
1112

@@ -125,6 +126,18 @@ func TestTransportPerform(t *testing.T) {
125126
}
126127
})
127128

129+
t.Run("Sets UserAgent", func(t *testing.T) {
130+
u, _ := url.Parse("http://example.com")
131+
tp := New(Config{URLs: []*url.URL{u}})
132+
133+
req, _ := http.NewRequest("GET", "/abc", nil)
134+
tp.setUserAgent(req)
135+
136+
if !strings.HasPrefix(req.UserAgent(), "go-elasticsearch") {
137+
t.Errorf("Unexpected user agent: %s", req.UserAgent())
138+
}
139+
})
140+
128141
t.Run("Error No URL", func(t *testing.T) {
129142
tp := New(Config{
130143
URLs: []*url.URL{},

0 commit comments

Comments
 (0)