Import upstream version 0.0~git20190921.0.7961383
Debian Janitor
1 year, 3 months ago
23 | 23 | package client |
24 | 24 | |
25 | 25 | import ( |
26 | "context" | |
26 | 27 | "encoding/json" |
27 | 28 | "errors" |
28 | 29 | "fmt" |
426 | 427 | return &clientImpl, nil |
427 | 428 | } |
428 | 429 | |
430 | // ClientContext implements the Client interface and additionally provides a | |
431 | // way to return a client that is associated with the given context. | |
432 | type ClientContext interface { | |
433 | // WithContext returns a Client that is associated with the given context. | |
434 | // Use this to pass a context to underlying transport (e.g. to specify a | |
435 | // deadline). | |
436 | WithContext(ctx context.Context) Client | |
437 | Client | |
438 | } | |
439 | ||
440 | func NewClientContext(opentsdbCfg config.OpenTSDBConfig) (Client, error) { | |
441 | client, err := NewClient(opentsdbCfg) | |
442 | if err != nil { | |
443 | return nil, err | |
444 | } | |
445 | // We know this is actually clientImpl and implements this interface. | |
446 | return client.(ClientContext), nil | |
447 | } | |
448 | ||
429 | 449 | // The private implementation of Client interface. |
430 | 450 | type clientImpl struct { |
431 | 451 | tsdbEndpoint string |
432 | 452 | client *http.Client |
453 | ctx context.Context | |
433 | 454 | opentsdbCfg config.OpenTSDBConfig |
434 | 455 | } |
435 | 456 | |
452 | 473 | // Return the contents of the specific Response instance with |
453 | 474 | // the string format |
454 | 475 | String() string |
476 | } | |
477 | ||
478 | func (c *clientImpl) WithContext(ctx context.Context) Client { | |
479 | return &clientImpl{ | |
480 | tsdbEndpoint: c.tsdbEndpoint, | |
481 | client: c.client, | |
482 | ctx: ctx, | |
483 | opentsdbCfg: c.opentsdbCfg, | |
484 | } | |
455 | 485 | } |
456 | 486 | |
457 | 487 | // sendRequest dispatches the http request with the given method name, url and body contents. |
460 | 490 | // response with the specific type. Otherwise, the returned error is not nil. |
461 | 491 | func (c *clientImpl) sendRequest(method, url, reqBodyCnt string, parsedResp Response) error { |
462 | 492 | req, err := http.NewRequest(method, url, strings.NewReader(reqBodyCnt)) |
493 | if c.ctx != nil { | |
494 | req = req.WithContext(c.ctx) | |
495 | } | |
463 | 496 | if err != nil { |
464 | 497 | return errors.New(fmt.Sprintf("Failed to create request for %s %s: %v", method, url, err)) |
465 | 498 | } |