This repository has been archived by the owner on May 29, 2019. It is now read-only.
forked from beatlabs/patron
/
http.go
82 lines (68 loc) · 1.82 KB
/
http.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
72
73
74
75
76
77
78
79
80
81
82
package http
import (
"context"
"net/http"
"time"
"github.com/opentracing-contrib/go-stdlib/nethttp"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/thebeatapp/patron/reliability/circuitbreaker"
"github.com/thebeatapp/patron/trace"
)
// Client interface of a HTTP client.
type Client interface {
Do(ctx context.Context, req *http.Request) (*http.Response, error)
}
// TracedClient defines a HTTP client with tracing integrated.
type TracedClient struct {
cl *http.Client
cb *circuitbreaker.CircuitBreaker
}
// New creates a new HTTP client.
func New(oo ...OptionFunc) (*TracedClient, error) {
tc := &TracedClient{
cl: &http.Client{
Timeout: 60 * time.Second,
Transport: &nethttp.Transport{},
},
cb: nil,
}
for _, o := range oo {
err := o(tc)
if err != nil {
return nil, err
}
}
return tc, nil
}
// Do executes a HTTP request with integrated tracing and tracing propagation downstream.
func (tc *TracedClient) Do(ctx context.Context, req *http.Request) (*http.Response, error) {
req = req.WithContext(ctx)
req, ht := nethttp.TraceRequest(
opentracing.GlobalTracer(),
req,
nethttp.OperationName(trace.HTTPOpName(req.Method, req.URL.String())),
nethttp.ComponentName(trace.HTTPClientComponent))
defer ht.Finish()
rsp, err := tc.do(req)
if err != nil {
ext.Error.Set(ht.Span(), true)
} else {
ext.HTTPStatusCode.Set(ht.Span(), uint16(rsp.StatusCode))
}
ext.HTTPMethod.Set(ht.Span(), req.Method)
ext.HTTPUrl.Set(ht.Span(), req.URL.String())
return rsp, err
}
func (tc *TracedClient) do(req *http.Request) (*http.Response, error) {
if tc.cb == nil {
return tc.cl.Do(req)
}
r, err := tc.cb.Execute(func() (interface{}, error) {
return tc.cl.Do(req)
})
if err != nil {
return nil, err
}
return r.(*http.Response), nil
}