/
sync.go
90 lines (75 loc) · 2.02 KB
/
sync.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 proxy
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
type Syncer struct {
UpstreamURL string
SyncParams url.Values
// our client for the upstream connection
client http.Client
}
// an error returned when the /sync endpoint returns a non-200.
type SyncError struct {
StatusCode int
ContentType string
Body []byte
}
func (s *SyncError) Error() string {
return string(s.Body)
}
// MakeRequest sends the sync request, and returns the body of the response,
// or an error.
//
// It keeps track of the 'next_batch' from the result, and uses it to se the
// 'since' parameter for the next call.
//
// Note that this method is not thread-safe; there should be only one concurrent
// call per Syncer.
//
// If /sync returns a non-200 response, the error returned will be a SyncError.
func (s *Syncer) MakeRequest() ([]byte, error) {
url := s.UpstreamURL + "?" + s.SyncParams.Encode()
log.Println("request", url)
resp, err := s.client.Get(url)
if err != nil {
log.Println("Error in sync", err)
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading sync error response: %v", err)
}
log.Println("Sync response:", resp.StatusCode)
if resp.StatusCode != 200 {
return nil, &SyncError{resp.StatusCode, resp.Header.Get("Content-Type"), body}
}
// we need the 'next_batch' token, so fish that out
next_batch, err := extractNextBatch(body)
if err != nil {
return nil, err
}
log.Println("Got next_batch:", next_batch)
s.SyncParams.Set("since", next_batch)
return body, nil
}
// extractNextBatch fishes the 'next_batch' member out of the JSON response from
// /sync.
func extractNextBatch(httpBody []byte) (string, error) {
type syncResponse struct {
NextBatch string `json:"next_batch"`
}
var sr syncResponse
if err := json.Unmarshal(httpBody, &sr); err != nil {
return "", err
}
if sr.NextBatch == "" {
return "", fmt.Errorf("/sync response missing next_batch")
}
return sr.NextBatch, nil
}