-
Notifications
You must be signed in to change notification settings - Fork 11
/
reddit.go
59 lines (46 loc) · 1.06 KB
/
reddit.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
package popularity
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
)
type Reddit struct{}
type redditResult struct {
Data struct {
Children []struct {
Data struct {
Score int64 `json:"score"`
Comments int64 `json:"num_comments"`
} `json:"data"`
} `json:"children"`
} `json:"data"`
}
func (r Reddit) Score(link string) (int64, error) {
var score int64 = -1
link = url.QueryEscape(link)
resp, err := http.Get("http://buttons.reddit.com/button_info.json?url=" + link)
if err != nil {
return score, err
}
defer func() {
// Drain the body so that the connection can be reused
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}()
dec := json.NewDecoder(resp.Body)
var result redditResult
if err := dec.Decode(&result); err != nil {
return score, fmt.Errorf("Error scoring link %s using reddit: %v", link, err)
}
score = 0
for _, d := range result.Data.Children {
score += d.Data.Score + d.Data.Comments
}
return score, nil
}
func (re Reddit) String() string {
return "Reddit score provider"
}