-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetcher.go
89 lines (80 loc) · 1.99 KB
/
fetcher.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
package blogplus
import (
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
)
var (
BaseURL = "https://www.googleapis.com/plus/v1/"
)
type Fetcher struct {
userId string
key string
mu sync.Mutex
fetchETag string
}
func NewFetcher(userId, key string) *Fetcher {
fetcher := &Fetcher{userId: userId, key: key}
return fetcher
}
func (fetcher *Fetcher) GetActivities(client *http.Client, pageToken string) (*ActivityFeed, error) {
url := BaseURL + "people/" + fetcher.userId + "/activities/public?num=100&key=" + fetcher.key
if pageToken != "" {
url += "&pageToken=" + pageToken
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
if pageToken != "" {
fetcher.mu.Lock()
if fetcher.fetchETag != "" {
req.Header.Add("If-None-Match", fetcher.fetchETag)
}
fetcher.mu.Unlock()
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if pageToken != "" {
fetcher.mu.Lock()
fetcher.fetchETag = resp.Header.Get("ETag")
fetcher.mu.Unlock()
}
var data ActivityFeed
err = json.NewDecoder(resp.Body).Decode(&data)
return &data, err
}
func (fetcher *Fetcher) getSinglePost(client *http.Client, activityId string) (post Activity, err error) {
url := BaseURL + fmt.Sprintf("activities/%s?num=100&key=%s", activityId, fetcher.key)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return post, err
}
resp, err := client.Do(req)
if err != nil {
return post, err
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&post)
return post, err
}
func (fetcher *Fetcher) Fetch(client *http.Client) []Activity {
activityFeed, err := fetcher.GetActivities(client, "")
if err != nil {
log.Println("getActivities:", err)
}
return activityFeed.Items
}
func (fetcher *Fetcher) FetchPost(client *http.Client, activityId string) []Activity {
activity, err := fetcher.getSinglePost(client, activityId)
if err != nil {
log.Println("getSinglePost:", err)
return nil
}
return []Activity{activity}
}