-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_client.go
More file actions
64 lines (53 loc) · 1.45 KB
/
http_client.go
File metadata and controls
64 lines (53 loc) · 1.45 KB
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
package tracing
import (
"context"
"net/http"
)
type HTTPClient interface {
Do(*http.Request) (*http.Response, error)
Get(string) (*http.Response, error)
}
type wrappedClient struct {
HTTPClient
ctx context.Context
}
func WrapClient(c HTTPClient) HTTPClient {
return &wrappedClient{HTTPClient: c}
}
func WrapClientWithContext(ctx context.Context, c HTTPClient) HTTPClient {
return &wrappedClient{HTTPClient: c, ctx: ctx}
}
func (c *wrappedClient) Do(req *http.Request) (res *http.Response, err error) {
ctx, span := Trace(req.Context(), req.URL.Host, WithSpanKind(SpanKindClient))
defer func() {
if err != nil {
span.RecordError(err)
} else {
span.SetMetadata(map[string]any{
"http.status_code": res.StatusCode,
"http.response_content_length": res.ContentLength,
})
span.SetStatus(res.StatusCode)
}
span.End()
}()
span.SetMetadata(map[string]any{
"http.method": req.Method,
"http.url": req.URL.String(),
"http.scheme": req.URL.Scheme,
"http.query": req.URL.RawQuery,
"http.path": req.URL.Path,
"http.request_content_length": req.ContentLength,
})
return c.HTTPClient.Do(req.WithContext(ctx))
}
func (c *wrappedClient) Get(url string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
if c.ctx != nil {
req = req.WithContext(c.ctx)
}
return c.Do(req)
}