-
Notifications
You must be signed in to change notification settings - Fork 1.1k
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 (see docs).
Another example of using your own http.Transport
is e.g. HTTP Basic Authentication. Here's how to do HTTP Basic Authentication 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))