forked from onedotover/go-getstream
/
client.go
209 lines (174 loc) · 4.25 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package getstream
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"log"
)
type Client struct {
http *http.Client
baseURL *url.URL // https://api.getstream.io/api/
key string
secret string
appID string
location string // https://location-api.getstream.io/api/
}
func Connect(key, secret, appID, location string) *Client {
baseURLStr := "https://api.getstream.io/api/v1.0/"
if location != "" {
baseURLStr = "https://" + location + "-api.getstream.io/api/v1.0/"
}
baseURL, e := url.Parse(baseURLStr)
if e != nil {
panic(e) // failfast, url shouldn't be invalid anyway.
}
return &Client{
http: &http.Client{},
baseURL: baseURL,
key: key,
secret: secret,
appID: appID,
location: location,
}
}
func (c *Client) BaseURL() *url.URL { return c.baseURL }
func (c *Client) Feed(slug, id string) *Feed {
s := Slug{slug, id, ""}
s.Sign(c.secret)
return &Feed{
Client: c,
slug: s,
}
}
func (c *Client) get(result interface{}, path string, slug Slug, params interface{}) error {
path, err := addPathParams(path, params)
if err != nil {
return err
}
return c.request(result, "GET", path, slug, nil)
}
func (c *Client) post(result interface{}, path string, slug Slug, payload interface{}) error {
return c.request(result, "POST", path, slug, payload)
}
func (c *Client) del(path string, slug Slug) error {
return c.request(nil, "DELETE", path, slug, nil)
}
func (c *Client) request(result interface{}, method, path string, slug Slug, payload interface{}) error {
absUrl, e := c.absoluteUrl(path)
if e != nil {
return e
}
buffer := []byte{}
if payload != nil {
if buffer, e = json.Marshal(payload); e != nil {
return e
}
}
req, e := http.NewRequest(method, absUrl.String(), bytes.NewBuffer(buffer))
if e != nil {
return e
}
req.Header.Set("Content-Type", "application/json")
if slug.Token != "" {
req.Header.Set("Authorization", slug.Signature())
}
resp, e := c.http.Do(req)
if e != nil {
return e
}
defer resp.Body.Close()
buffer, e = ioutil.ReadAll(resp.Body)
if e != nil {
return e
}
switch {
case 200 <= resp.StatusCode && resp.StatusCode < 300: // SUCCESS
if result != nil {
// log.Println("Response", absUrl.String(), string(buffer));
if e = json.Unmarshal(buffer, result); e != nil {
return e
}
}
default:
err := &Error{}
if e = json.Unmarshal(buffer, err); e != nil {
log.Println("err", absUrl)
return errors.New(string(buffer))
}
return err
}
return nil
}
func (c *Client) absoluteUrl(path string) (result *url.URL, e error) {
if result, e = url.Parse(path); e != nil {
return nil, e
}
// DEBUG: Use this line to send stuff to a proxy instead.
// c.baseURL, _ = url.Parse("http://0.0.0.0:8000/")
result = c.baseURL.ResolveReference(result)
qs := result.Query()
qs.Set("api_key", c.key)
if c.location == "" {
qs.Set("location", "unspecified")
} else {
qs.Set("location", c.location)
}
result.RawQuery = qs.Encode()
return result, nil
}
func addPathParams(path string, params interface{}) (string, error) {
// Simple conversion from struct to query parameters
// Only supports basic conversion.
val := reflect.ValueOf(params)
if val.IsNil() {
return path, nil
}
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
if val.Kind() != reflect.Struct {
return path, errors.New("Params must be a struct.")
}
url, err := url.Parse(path)
if err != nil {
return path, err
}
// Convert the params obejct into query parameters
query := url.Query()
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
typField := typ.Field(i)
if typField.PkgPath != "" {
continue // unexported
}
tag := typField.Tag.Get("url")
if tag == "-" {
continue
}
// @todo: Add support for more types or utilize url encoding package like
// https://github.com/google/go-querystring
value := ""
valField := val.Field(i)
switch valField.Kind() {
case reflect.String:
value = valField.String()
case reflect.Int:
if valField.Int() != 0 {
value = fmt.Sprintf("%d", valField)
}
default:
value = fmt.Sprintf("%v", valField)
}
// If we have a value set, add it to the query
if value != "" {
query.Set(tag, value)
}
}
url.RawQuery = query.Encode()
return url.String(), nil
}