-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathclient.go
102 lines (82 loc) · 1.45 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
91
92
93
94
95
96
97
98
99
100
101
102
package client
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Client struct {
http.Client
Conf *Config
Cache *Cache
}
type Config struct {
Host string `json:"host"`
DisableCache bool `json:"disable_cache"`
Header http.Header
}
type APIResponse struct {
Response *http.Response
JSON []byte
Data []map[string]interface{}
}
// QueryOptions holds options for a query
type QueryOptions struct {
Count int
Offset int
Order string
}
func New(cfg *Config) *Client {
c := &Client{
Conf: cfg,
}
if cfg.DisableCache {
return c
}
c.Cache = NewCache()
return c
}
func (c *Client) CacheEnabled() bool {
return !c.Conf.DisableCache
}
func (a *APIResponse) process() error {
jsn, err := ioutil.ReadAll(a.Response.Body)
if err != nil {
return err
}
if len(jsn) == 0 {
return fmt.Errorf("%s", a.Response.Status)
}
data := make(map[string][]map[string]interface{})
err = json.Unmarshal(jsn, &data)
if err != nil {
return err
}
a.JSON = jsn
a.Data = data["data"]
return nil
}
func setDefaultOpts(opts *QueryOptions) *QueryOptions {
if opts == nil {
opts = &QueryOptions{
Count: 10,
Order: "DESC",
Offset: 0,
}
}
if opts.Count == 0 {
opts.Count = 10
}
if opts.Order == "" {
opts.Order = "DESC"
}
return opts
}
func mergeHeader(req *http.Request, header http.Header) *http.Request {
for k, v := range header {
for i := range v {
req.Header.Add(k, v[i])
}
}
return req
}