forked from olivere/elastic
/
transport.go
71 lines (60 loc) · 1.8 KB
/
transport.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2012-present Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.
package opentracing
import (
"net/http"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
)
// Transport for tracing Elastic operations.
type Transport struct {
rt http.RoundTripper
}
// Option signature for specifying options, e.g. WithRoundTripper.
type Option func(t *Transport)
// WithRoundTripper specifies the http.RoundTripper to call
// next after this transport. If it is nil (default), the
// transport will use http.DefaultTransport.
func WithRoundTripper(rt http.RoundTripper) Option {
return func(t *Transport) {
t.rt = rt
}
}
// NewTransport specifies a transport that will trace Elastic
// and report back via OpenTracing.
func NewTransport(opts ...Option) *Transport {
t := &Transport{}
for _, o := range opts {
o(t)
}
return t
}
// RoundTrip captures the request and starts an OpenTracing span
// for Elastic PerformRequest operation.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
span, ctx := opentracing.StartSpanFromContext(req.Context(), "PerformRequest")
req = req.WithContext(ctx)
defer span.Finish()
ext.Component.Set(span, "github.com/olivere/elastic/v6")
ext.HTTPUrl.Set(span, req.URL.String())
ext.HTTPMethod.Set(span, req.Method)
ext.PeerHostname.Set(span, req.URL.Hostname())
ext.PeerPort.Set(span, atouint16(req.URL.Port()))
var (
resp *http.Response
err error
)
if t.rt != nil {
resp, err = t.rt.RoundTrip(req)
} else {
resp, err = http.DefaultTransport.RoundTrip(req)
}
if err != nil {
ext.Error.Set(span, true)
}
if resp != nil {
ext.HTTPStatusCode.Set(span, uint16(resp.StatusCode))
}
return resp, err
}