-
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
client.go
365 lines (339 loc) · 9.36 KB
/
client.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
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package blademaster
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net"
xhttp "net/http"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/bilibili/kratos/pkg/conf/env"
"github.com/bilibili/kratos/pkg/net/metadata"
"github.com/bilibili/kratos/pkg/net/netutil/breaker"
xtime "github.com/bilibili/kratos/pkg/time"
"github.com/gogo/protobuf/proto"
pkgerr "github.com/pkg/errors"
)
const (
_minRead = 16 * 1024 // 16kb
)
var (
_noKickUserAgent = "blademaster"
)
func init() {
n, err := os.Hostname()
if err == nil {
_noKickUserAgent = _noKickUserAgent + runtime.Version() + " " + n
}
}
// ClientConfig is http client conf.
type ClientConfig struct {
Dial xtime.Duration
Timeout xtime.Duration
KeepAlive xtime.Duration
Breaker *breaker.Config
URL map[string]*ClientConfig
Host map[string]*ClientConfig
}
// Client is http client.
type Client struct {
conf *ClientConfig
client *xhttp.Client
dialer *net.Dialer
transport xhttp.RoundTripper
urlConf map[string]*ClientConfig
hostConf map[string]*ClientConfig
mutex sync.RWMutex
breaker *breaker.Group
}
// NewClient new a http client.
func NewClient(c *ClientConfig) *Client {
client := new(Client)
client.conf = c
client.dialer = &net.Dialer{
Timeout: time.Duration(c.Dial),
KeepAlive: time.Duration(c.KeepAlive),
}
originTransport := &xhttp.Transport{
DialContext: client.dialer.DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
// wraps RoundTripper for tracer
client.transport = &TraceTransport{RoundTripper: originTransport}
client.client = &xhttp.Client{
Transport: client.transport,
}
client.urlConf = make(map[string]*ClientConfig)
client.hostConf = make(map[string]*ClientConfig)
client.breaker = breaker.NewGroup(c.Breaker)
if c.Timeout <= 0 {
panic("must config http timeout!!!")
}
for uri, cfg := range c.URL {
client.urlConf[uri] = cfg
}
for host, cfg := range c.Host {
client.hostConf[host] = cfg
}
return client
}
// SetTransport set client transport
func (client *Client) SetTransport(t xhttp.RoundTripper) {
client.transport = t
client.client.Transport = t
}
// SetConfig set client config.
func (client *Client) SetConfig(c *ClientConfig) {
client.mutex.Lock()
if c.Timeout > 0 {
client.conf.Timeout = c.Timeout
}
if c.KeepAlive > 0 {
client.dialer.KeepAlive = time.Duration(c.KeepAlive)
client.conf.KeepAlive = c.KeepAlive
}
if c.Dial > 0 {
client.dialer.Timeout = time.Duration(c.Dial)
client.conf.Timeout = c.Dial
}
if c.Breaker != nil {
client.conf.Breaker = c.Breaker
client.breaker.Reload(c.Breaker)
}
for uri, cfg := range c.URL {
client.urlConf[uri] = cfg
}
for host, cfg := range c.Host {
client.hostConf[host] = cfg
}
client.mutex.Unlock()
}
// NewRequest new http request with method, uri, ip, values and headers.
// TODO(zhoujiahui): param realIP should be removed later.
func (client *Client) NewRequest(method, uri, realIP string, params url.Values) (req *xhttp.Request, err error) {
if method == xhttp.MethodGet {
req, err = xhttp.NewRequest(xhttp.MethodGet, fmt.Sprintf("%s?%s", uri, params.Encode()), nil)
} else {
req, err = xhttp.NewRequest(xhttp.MethodPost, uri, strings.NewReader(params.Encode()))
}
if err != nil {
err = pkgerr.Wrapf(err, "method:%s,uri:%s", method, uri)
return
}
const (
_contentType = "Content-Type"
_urlencoded = "application/x-www-form-urlencoded"
_userAgent = "User-Agent"
)
if method == xhttp.MethodPost {
req.Header.Set(_contentType, _urlencoded)
}
if realIP != "" {
req.Header.Set(_httpHeaderRemoteIP, realIP)
}
req.Header.Set(_userAgent, _noKickUserAgent+" "+env.AppID)
return
}
// Get issues a GET to the specified URL.
func (client *Client) Get(c context.Context, uri, ip string, params url.Values, res interface{}) (err error) {
req, err := client.NewRequest(xhttp.MethodGet, uri, ip, params)
if err != nil {
return
}
return client.Do(c, req, res)
}
// Post issues a Post to the specified URL.
func (client *Client) Post(c context.Context, uri, ip string, params url.Values, res interface{}) (err error) {
req, err := client.NewRequest(xhttp.MethodPost, uri, ip, params)
if err != nil {
return
}
return client.Do(c, req, res)
}
// RESTfulGet issues a RESTful GET to the specified URL.
func (client *Client) RESTfulGet(c context.Context, uri, ip string, params url.Values, res interface{}, v ...interface{}) (err error) {
req, err := client.NewRequest(xhttp.MethodGet, fmt.Sprintf(uri, v...), ip, params)
if err != nil {
return
}
return client.Do(c, req, res, uri)
}
// RESTfulPost issues a RESTful Post to the specified URL.
func (client *Client) RESTfulPost(c context.Context, uri, ip string, params url.Values, res interface{}, v ...interface{}) (err error) {
req, err := client.NewRequest(xhttp.MethodPost, fmt.Sprintf(uri, v...), ip, params)
if err != nil {
return
}
return client.Do(c, req, res, uri)
}
// Raw sends an HTTP request and returns bytes response
func (client *Client) Raw(c context.Context, req *xhttp.Request, v ...string) (bs []byte, err error) {
var (
ok bool
code string
cancel func()
resp *xhttp.Response
config *ClientConfig
timeout time.Duration
uri = fmt.Sprintf("%s://%s%s", req.URL.Scheme, req.Host, req.URL.Path)
)
// NOTE fix prom & config uri key.
if len(v) == 1 {
uri = v[0]
}
// breaker
brk := client.breaker.Get(uri)
if err = brk.Allow(); err != nil {
code = "breaker"
_metricClientReqCodeTotal.Inc(uri, req.Method, code)
return
}
defer client.onBreaker(brk, &err)
// stat
now := time.Now()
defer func() {
_metricClientReqDur.Observe(int64(time.Since(now)/time.Millisecond), uri, req.Method)
if code != "" {
_metricClientReqCodeTotal.Inc(uri, req.Method, code)
}
}()
// get config
// 1.url config 2.host config 3.default
client.mutex.RLock()
if config, ok = client.urlConf[uri]; !ok {
if config, ok = client.hostConf[req.Host]; !ok {
config = client.conf
}
}
client.mutex.RUnlock()
// timeout
deliver := true
timeout = time.Duration(config.Timeout)
if deadline, ok := c.Deadline(); ok {
if ctimeout := time.Until(deadline); ctimeout < timeout {
// deliver small timeout
timeout = ctimeout
deliver = false
}
}
if deliver {
c, cancel = context.WithTimeout(c, timeout)
defer cancel()
}
setTimeout(req, timeout)
req = req.WithContext(c)
setCaller(req)
metadata.Range(c,
func(key string, value interface{}) {
setMetadata(req, key, value)
},
metadata.IsOutgoingKey)
if resp, err = client.client.Do(req); err != nil {
err = pkgerr.Wrapf(err, "host:%s, url:%s", req.URL.Host, realURL(req))
code = "failed"
return
}
defer resp.Body.Close()
if resp.StatusCode >= xhttp.StatusBadRequest {
err = pkgerr.Errorf("incorrect http status:%d host:%s, url:%s", resp.StatusCode, req.URL.Host, realURL(req))
code = strconv.Itoa(resp.StatusCode)
return
}
if bs, err = readAll(resp.Body, _minRead); err != nil {
err = pkgerr.Wrapf(err, "host:%s, url:%s", req.URL.Host, realURL(req))
return
}
return
}
// Do sends an HTTP request and returns an HTTP json response.
func (client *Client) Do(c context.Context, req *xhttp.Request, res interface{}, v ...string) (err error) {
var bs []byte
if bs, err = client.Raw(c, req, v...); err != nil {
return
}
if res != nil {
if err = json.Unmarshal(bs, res); err != nil {
err = pkgerr.Wrapf(err, "host:%s, url:%s", req.URL.Host, realURL(req))
}
}
return
}
// JSON sends an HTTP request and returns an HTTP json response.
func (client *Client) JSON(c context.Context, req *xhttp.Request, res interface{}, v ...string) (err error) {
var bs []byte
if bs, err = client.Raw(c, req, v...); err != nil {
return
}
if res != nil {
if err = json.Unmarshal(bs, res); err != nil {
err = pkgerr.Wrapf(err, "host:%s, url:%s", req.URL.Host, realURL(req))
}
}
return
}
// PB sends an HTTP request and returns an HTTP proto response.
func (client *Client) PB(c context.Context, req *xhttp.Request, res proto.Message, v ...string) (err error) {
var bs []byte
if bs, err = client.Raw(c, req, v...); err != nil {
return
}
if res != nil {
if err = proto.Unmarshal(bs, res); err != nil {
err = pkgerr.Wrapf(err, "host:%s, url:%s", req.URL.Host, realURL(req))
}
}
return
}
func (client *Client) onBreaker(breaker breaker.Breaker, err *error) {
if err != nil && *err != nil {
breaker.MarkFailed()
} else {
breaker.MarkSuccess()
}
}
// realUrl return url with http://host/params.
func realURL(req *xhttp.Request) string {
if req.Method == xhttp.MethodGet {
return req.URL.String()
} else if req.Method == xhttp.MethodPost {
ru := req.URL.Path
if req.Body != nil {
rd, ok := req.Body.(io.Reader)
if ok {
buf := bytes.NewBuffer([]byte{})
buf.ReadFrom(rd)
ru = ru + "?" + buf.String()
}
}
return ru
}
return req.URL.Path
}
// readAll reads from r until an error or EOF and returns the data it read
// from the internal buffer allocated with a specified capacity.
func readAll(r io.Reader, capacity int64) (b []byte, err error) {
buf := bytes.NewBuffer(make([]byte, 0, capacity))
// If the buffer overflows, we will get bytes.ErrTooLarge.
// Return that as an error. Any other panic remains.
defer func() {
e := recover()
if e == nil {
return
}
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
err = panicErr
} else {
panic(e)
}
}()
_, err = buf.ReadFrom(r)
return buf.Bytes(), err
}