-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathclient.go
More file actions
115 lines (102 loc) · 2.57 KB
/
client.go
File metadata and controls
115 lines (102 loc) · 2.57 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
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
package druid
import (
"encoding/json"
"net/url"
"strings"
"time"
"github.com/hashicorp/go-retryablehttp"
)
const (
processInformationPathPrefix = "status/"
coordinatorPathPrefix = "druid/coordinator/v1/"
overlordPathPrefix = "druid/indexer/v1/"
middleManagerPathPrefix = "druid/worker/v1/"
peonPathPrefix = "druid/worker/v1/chat/"
historicalPathPrefix = "druid/historical/v1/"
defaultRetryWaitMin = 100 * time.Millisecond
defaultRetryWaitMax = 3 * time.Second
defaultRetryMax = 5
)
var defaultBackoff = retryablehttp.DefaultBackoff
type Client struct {
http *retryablehttp.Client
baseURL *url.URL
username string
password string
basicAuth bool
}
func NewClient(baseURL string, options ...ClientOption) (*Client, error) {
opts := &clientOptions{
httpClient: defaultHTTPClient(),
backoff: defaultBackoff,
errorHandler: defaultErrorHandler,
retry: defaultRetry,
retryWaitMin: defaultRetryWaitMin,
retryWaitMax: defaultRetryWaitMax,
retryMax: defaultRetryMax,
}
for _, opt := range options {
opt(opts)
}
c := &Client{
http: &retryablehttp.Client{
Backoff: opts.backoff,
CheckRetry: opts.retry,
HTTPClient: opts.httpClient,
RetryWaitMin: opts.retryWaitMin,
RetryWaitMax: opts.retryWaitMax,
RetryMax: opts.retryMax,
},
username: opts.username,
password: opts.password,
basicAuth: opts.username != "" && opts.password != "",
}
if err := c.setBaseURL(baseURL); err != nil {
return nil, err
}
return c, nil
}
func (c *Client) Close() error {
return nil
}
func (c *Client) Do(r *retryablehttp.Request, result any) (*Response, error) {
resp, err := c.http.Do(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
response := &Response{resp}
if err = response.ExtractError(); err != nil {
return nil, err
}
if result != nil {
if err = json.NewDecoder(resp.Body).Decode(result); err != nil {
return nil, err
}
}
return response, nil
}
func (c *Client) ExecuteRequest(method, path string, opt, result any) (*Response, error) {
req, err := c.NewRequest(method, path, opt)
if err != nil {
return nil, err
}
return c.Do(req, result)
}
func (c *Client) setBaseURL(urlStr string) error {
if !strings.HasSuffix(urlStr, "/") {
urlStr += "/"
}
baseURL, err := url.ParseRequestURI(urlStr)
if err != nil {
return err
}
c.baseURL = baseURL
return nil
}
func (c *Client) Common() *CommonService {
return &CommonService{client: c}
}
func (c *Client) Query() *QueryService {
return &QueryService{client: c}
}