-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient_configuration.go
86 lines (73 loc) · 2.53 KB
/
client_configuration.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
// Copyright (c) Omlox Client Go Contributors
// SPDX-License-Identifier: MIT
package omlox
import (
"fmt"
"net/http"
"time"
"github.com/hashicorp/go-cleanhttp"
"golang.org/x/time/rate"
)
// GetDefaultOptions returns default configuration options for the client.
func DefaultConfiguration() ClientConfiguration {
// Use cleanhttp, which has the same default values as net/http client, but
// does not share state with other clients (see: gh/hashicorp/go-cleanhttp)
defaultClient := cleanhttp.DefaultPooledClient()
return ClientConfiguration{
HTTPClient: defaultClient,
RequestTimeout: 60 * time.Second,
}
}
// / ClientConfiguration is used to configure the creation of the client.
type ClientConfiguration struct {
// HTTPClient is the HTTP client to use for all API requests.
HTTPClient *http.Client
// RequestTimeout, given a non-negative value, will apply the timeout to
// each request function unless an earlier deadline is passed to the
// request function through context.Context.
//
// Default: 60s
RequestTimeout time.Duration
// RateLimiter controls how frequently requests are allowed to happen.
// If this pointer is nil, then there will be no limit set. Note that an
// empty struct rate.Limiter is equivalent to blocking all requests.
//
// Default: nil
RateLimiter *rate.Limiter
// UserAgent sets a name for the http client User-Agent header.
UserAgent string
}
// ClientOption is a configuration option to initialize a client.
type ClientOption func(*ClientConfiguration) error
// WithHTTPClient sets the HTTP client to use for all API requests.
func WithHTTPClient(client *http.Client) ClientOption {
return func(c *ClientConfiguration) error {
c.HTTPClient = client
return nil
}
}
// WithRequestTimeout, given a non-negative value, will apply the timeout to
// each request function unless an earlier deadline is passed to the request
// function through context.Context.
//
// Default: 60s
func WithRequestTimeout(timeout time.Duration) ClientOption {
return func(c *ClientConfiguration) error {
if timeout < 0 {
return fmt.Errorf("request timeout must not be negative")
}
c.RequestTimeout = timeout
return nil
}
}
// WithRateLimiter configures how frequently requests are allowed to happen.
// If this pointer is nil, then there will be no limit set. Note that an
// empty struct rate.Limiter is equivalent to blocking all requests.
//
// Default: nil
func WithRateLimiter(limiter *rate.Limiter) ClientOption {
return func(c *ClientConfiguration) error {
c.RateLimiter = limiter
return nil
}
}