This repository has been archived by the owner on May 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
firebase.go
305 lines (244 loc) · 6.86 KB
/
firebase.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// Package firebase impleements a RESTful client for Firebase.
package firebase
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
)
// Api is the interface for interacting with Firebase.
// Consumers of this package can mock this interface for testing purposes.
type Api interface {
Call(method, path, auth string, body []byte, params map[string]string) ([]byte, error)
}
// Client is the Firebase client.
type Client struct {
// Url is the client's base URL used for all calls.
Url string
// Auth is authentication token used when making calls.
// The token is optional and can also be overwritten on an individual
// call basis via params.
Auth string
// api is the underlying client used to make calls.
api Api
// value is the value of the object at the current Url
value interface{}
}
// Rules is the structure for security rules.
type Rules map[string]interface{}
// f is the internal implementation of the Firebase API client.
type f struct{}
// suffix is the Firebase suffix for invoking their API via HTTP
const suffix = ".json"
var (
connectTimeout = time.Duration(10 * time.Second) // timeout for http connection
readWriteTimeout = time.Duration(10 * time.Second) // timeout for http read/write
)
// httpClient is the HTTP client used to make calls to Firebase
var httpClient = newTimeoutClient(connectTimeout, readWriteTimeout)
// Init initializes the Firebase client with a given root url and optional auth token.
// The initialization can also pass a mock api for testing purposes.
func (c *Client) Init(root, auth string, api Api) {
if api == nil {
api = new(f)
}
c.api = api
c.Url = root
c.Auth = auth
}
// Value returns the value of of the current Url.
func (c *Client) Value() interface{} {
// if we have not yet performed a look-up, do it so a value is returned
if c.value == nil {
var v interface{}
c = c.Child("", nil, v)
}
if c == nil {
return nil
}
return c.value
}
// Child returns a populated pointer for a given path.
// If the path cannot be found, a null pointer is returned.
func (c *Client) Child(path string, params map[string]string, v interface{}) *Client {
u := c.Url + "/" + path
res, err := c.api.Call("GET", u, c.Auth, nil, params)
if err != nil {
return nil
}
err = json.Unmarshal(res, &v)
if err != nil {
log.Printf("%v\n", err)
return nil
}
ret := &Client{
api: c.api,
Auth: c.Auth,
Url: u,
value: v}
return ret
}
// Push creates a new value under the current root url.
// A populated pointer with that value is also returned.
func (c *Client) Push(value interface{}, params map[string]string) (*Client, error) {
body, err := json.Marshal(value)
if err != nil {
log.Printf("%v\n", err)
return nil, err
}
res, err := c.api.Call("POST", c.Url, c.Auth, body, params)
if err != nil {
return nil, err
}
var r map[string]string
err = json.Unmarshal(res, &r)
if err != nil {
log.Printf("%v\n", err)
return nil, err
}
ret := &Client{
api: c.api,
Auth: c.Auth,
Url: c.Url + "/" + r["name"],
value: value}
return ret, nil
}
// Set overwrites the value at the specified path and returns populated pointer
// for the updated path.
func (c *Client) Set(path string, value interface{}, params map[string]string) (*Client, error) {
u := c.Url + "/" + path
body, err := json.Marshal(value)
if err != nil {
log.Printf("%v\n", err)
return nil, err
}
res, err := c.api.Call("PUT", u, c.Auth, body, params)
if err != nil {
return nil, err
}
ret := &Client{
api: c.api,
Auth: c.Auth,
Url: u}
if len(res) > 0 {
var r interface{}
err = json.Unmarshal(res, &r)
if err != nil {
log.Printf("%v\n", err)
return nil, err
}
ret.value = r
}
return ret, nil
}
// Update performs a partial update with the given value at the specified path.
func (c *Client) Update(path string, value interface{}, params map[string]string) error {
body, err := json.Marshal(value)
if err != nil {
log.Printf("%v\n", err)
return err
}
_, err = c.api.Call("PATCH", c.Url+"/"+path, c.Auth, body, params)
// if we've just updated the root node, clear the value so it gets looked up
// again and populated correctly since we just applied a diffgram
if len(path) == 0 {
c.value = nil
}
return err
}
// Remove deletes the data at the given path.
func (c *Client) Remove(path string, params map[string]string) error {
_, err := c.api.Call("DELETE", c.Url+"/"+path, c.Auth, nil, params)
return err
}
// Rules returns the security rules for the database.
func (c *Client) Rules(params map[string]string) (Rules, error) {
res, err := c.api.Call("GET", c.Url+"/.settings/rules", c.Auth, nil, params)
if err != nil {
return nil, err
}
var v Rules
err = json.Unmarshal(res, &v)
if err != nil {
log.Printf("%v\n", err)
return nil, err
}
return v, nil
}
// SetRules overwrites the existing security rules with the new rules given.
func (c *Client) SetRules(rules *Rules, params map[string]string) error {
body, err := json.Marshal(rules)
if err != nil {
log.Printf("%v\n", err)
return err
}
_, err = c.api.Call("PUT", c.Url+"/.settings/rules", c.Auth, body, params)
return err
}
// Call invokes the appropriate HTTP method on a given Firebase URL.
func (f *f) Call(method, path, auth string, body []byte, params map[string]string) ([]byte, error) {
if !strings.HasSuffix(path, "/") {
path += "/"
}
path += suffix
qs := url.Values{}
// if the client has an auth, set it as a query string.
// the caller can also override this on a per-call basis
// which will happen via params below
if len(auth) > 0 {
qs.Set("auth", auth)
}
for k, v := range params {
qs.Set(k, v)
}
if len(qs) > 0 {
path += "?" + qs.Encode()
}
req, err := http.NewRequest(method, path, bytes.NewReader(body))
if err != nil {
log.Printf("Cannot create Firebase request: %v\n", err)
return nil, err
}
req.Close = true
log.Printf("Calling %v %q\n", method, path)
res, err := httpClient.Do(req)
if err != nil {
log.Printf("Request to Firebase failed: %v\n", err)
return nil, err
}
defer res.Body.Close()
ret, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Printf("Cannot parse Firebase response: %v\n", err)
return nil, err
}
if res.StatusCode >= 400 {
err = errors.New(string(ret))
log.Printf("Error encountered from Firebase: %v\n", err)
return nil, err
}
return ret, nil
}
func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) {
return func(netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, cTimeout)
if err != nil {
return nil, err
}
conn.SetDeadline(time.Now().Add(rwTimeout))
return conn, nil
}
}
func newTimeoutClient(connectTimeout time.Duration, readWriteTimeout time.Duration) *http.Client {
return &http.Client{
Transport: &http.Transport{
Dial: TimeoutDialer(connectTimeout, readWriteTimeout),
},
}
}