File: client.go

package info (click to toggle)
golang-github-openzipkin-zipkin-go 0.4.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 712 kB
  • sloc: makefile: 23
file content (153 lines) | stat: -rw-r--r-- 4,177 bytes parent folder | download
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// Copyright 2022 The OpenZipkin Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package http

import (
	"errors"
	"net/http"
	"strconv"
	"time"

	"github.com/openzipkin/zipkin-go"
	"github.com/openzipkin/zipkin-go/model"
)

// ErrValidTracerRequired error
var ErrValidTracerRequired = errors.New("valid tracer required")

// Client holds a Zipkin instrumented HTTP Client.
type Client struct {
	*http.Client
	tracer           *zipkin.Tracer
	httpTrace        bool
	defaultTags      map[string]string
	transportOptions []TransportOption
	remoteEndpoint   *model.Endpoint
}

// ClientOption allows optional configuration of Client.
type ClientOption func(*Client)

// WithClient allows one to add a custom configured http.Client to use.
func WithClient(client *http.Client) ClientOption {
	return func(c *Client) {
		if client == nil {
			client = &http.Client{}
		}
		c.Client = client
	}
}

// ClientTrace allows one to enable Go's net/http/httptrace.
func ClientTrace(enabled bool) ClientOption {
	return func(c *Client) {
		c.httpTrace = enabled
	}
}

// ClientTags adds default Tags to inject into client application spans.
func ClientTags(tags map[string]string) ClientOption {
	return func(c *Client) {
		c.defaultTags = tags
	}
}

// TransportOptions passes optional Transport configuration to the internal
// transport used by Client.
func TransportOptions(options ...TransportOption) ClientOption {
	return func(c *Client) {
		c.transportOptions = options
	}
}

// WithRemoteEndpoint will set the remote endpoint for all spans.
func WithRemoteEndpoint(remoteEndpoint *model.Endpoint) ClientOption {
	return func(c *Client) {
		c.remoteEndpoint = remoteEndpoint
	}
}

// NewClient returns an HTTP Client adding Zipkin instrumentation around an
// embedded standard Go http.Client.
func NewClient(tracer *zipkin.Tracer, options ...ClientOption) (*Client, error) {
	if tracer == nil {
		return nil, ErrValidTracerRequired
	}

	c := &Client{tracer: tracer, Client: &http.Client{}}
	for _, option := range options {
		option(c)
	}

	c.transportOptions = append(
		c.transportOptions,
		// the following Client settings override provided transport settings.
		RoundTripper(c.Client.Transport),
		TransportTrace(c.httpTrace),
		TransportRemoteEndpoint(c.remoteEndpoint),
	)
	tr, err := NewTransport(tracer, c.transportOptions...)
	if err != nil {
		return nil, err
	}
	c.Client.Transport = tr

	return c, nil
}

// DoWithAppSpan wraps http.Client's Do with tracing using an application span.
func (c *Client) DoWithAppSpan(req *http.Request, name string) (*http.Response, error) {
	var parentContext model.SpanContext

	if span := zipkin.SpanFromContext(req.Context()); span != nil {
		parentContext = span.Context()
	}

	appSpan := c.tracer.StartSpan(name, zipkin.Parent(parentContext), zipkin.RemoteEndpoint(c.remoteEndpoint))

	zipkin.TagHTTPMethod.Set(appSpan, req.Method)
	zipkin.TagHTTPPath.Set(appSpan, req.URL.Path)

	res, err := c.Do(
		req.WithContext(zipkin.NewContext(req.Context(), appSpan)),
	)
	if err != nil {
		zipkin.TagError.Set(appSpan, err.Error())
		appSpan.Finish()
		return res, err
	}

	if c.httpTrace {
		appSpan.Annotate(time.Now(), "wr")
	}

	if res.ContentLength > 0 {
		zipkin.TagHTTPResponseSize.Set(appSpan, strconv.FormatInt(res.ContentLength, 10))
	}
	if res.StatusCode < 200 || res.StatusCode > 299 {
		statusCode := strconv.FormatInt(int64(res.StatusCode), 10)
		zipkin.TagHTTPStatusCode.Set(appSpan, statusCode)
		if res.StatusCode > 399 {
			zipkin.TagError.Set(appSpan, statusCode)
		}
	}

	res.Body = &spanCloser{
		ReadCloser:   res.Body,
		sp:           appSpan,
		traceEnabled: c.httpTrace,
	}
	return res, err
}