-
Notifications
You must be signed in to change notification settings - Fork 46
/
client.go
90 lines (77 loc) · 1.46 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
package godruid
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
const (
DefaultEndPoint = "/druid/v2"
)
type Client struct {
Url string
EndPoint string
Timeout time.Duration
Debug bool
LastRequest string
LastResponse string
}
func (c *Client) Query(query Query) (err error) {
query.setup()
var reqJson []byte
if c.Debug {
reqJson, err = json.MarshalIndent(query, "", " ")
} else {
reqJson, err = json.Marshal(query)
}
if err != nil {
return
}
result, err := c.QueryRaw(reqJson)
if err != nil {
return
}
return query.onResponse(result)
}
func (c *Client) QueryRaw(req []byte) (result []byte, err error) {
if c.EndPoint == "" {
c.EndPoint = DefaultEndPoint
}
endPoint := c.EndPoint
if c.Debug {
endPoint += "?pretty"
c.LastRequest = string(req)
}
if err != nil {
return
}
// By default, use 60 second timeout unless specified otherwise
// by the caller
clientTimeout := 60 * time.Second
if c.Timeout != 0 {
clientTimeout = c.Timeout
}
httpClient := &http.Client{
Timeout: clientTimeout,
}
resp, err := httpClient.Post(c.Url+endPoint, "application/json", bytes.NewBuffer(req))
if err != nil {
return
}
defer func() {
resp.Body.Close()
}()
result, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if c.Debug {
c.LastResponse = string(result)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %s", resp.Status, string(result))
}
return
}