forked from shunfei/godruid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
77 lines (66 loc) · 1.19 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
package godruid
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
const (
DefaultEndPoint = "/druid/v2"
)
type Client struct {
Url string
EndPoint string
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
}
resp, err := http.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
}