-
Notifications
You must be signed in to change notification settings - Fork 1.2k
HttpTransport
Oliver Eilhard edited this page Nov 15, 2015
·
12 revisions
For advanced scenarios, you can provide your own http.Client
/ http.Transport
. You need to create your own http.Client
, set its Transport
field, then configure the new client with elastic.SetHttpClient(...)
.
Here is an example that counts requests.
// CountingTransport will count requests.
type CountingTransport struct {
N int64 // number of requests passing this transport
next http.RoundTripper // next round-tripper or http.DefaultTransport if nil
}
// RoundTrip implements a transport that will count requests.
func (tr *CountingTransport) RoundTrip(r *http.Request) (*http.Response, error) {
atomic. AddInt64(&tr.N, 1)
if tr.next != nil {
return tr.next.RoundTrip(r)
}
return http.DefaultTransport.RoundTrip(r)
}
...
myHttpClient := &http.Client{Transport: &CountingTransport{}}
client, err := elastic.NewClient(elastic.SetHttpClient(myHttpClient))
Notice that this is just an example: You can use the SetBasicAuth
configuration setting for this now.
Another example of using your own http.Transport
is HTTP Basic Authentication. As HTTP Basic Authentication is a common use case, there is a elastic.SetBasicAuth("username", "password")
option that you can use when setting up a new Client (see docs). The SetBasicAuth
options is available since 2.0.13. Anyway, here's how to do that with your own http.Transport
:
// BasicAuthTransport
type BasicAuthTransport struct {
username string
password string
}
func (tr *BasicAuthTransport) RoundTrip(r *http.Request) (*http.Response, error) {
r.SetBasicAuth(tr.username, tr.password)
return http.DefaultTransport.RoundTrip(r)
}
...
httpClient = &http.Client{
Transport: &BasicAuthTransport{
username: "me",
password: "secret",
},
}
client, err := elastic.NewClient(elastic.SetHttpClient(httpClient))