-
Notifications
You must be signed in to change notification settings - Fork 0
/
reddit.go
60 lines (55 loc) · 1.13 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
60
// Package reddit implements a basic client for the Reddit API.
package reddit
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
type response struct {
Data struct {
Children []struct {
Data Item
}
}
}
// Item describes a Reddit item.
type Item struct {
Title string
URL string
Comments int `json:"num_comments"`
}
func (i Item) String() string {
com := ""
switch i.Comments {
case 0:
// nothing
case 1:
com = " (1 comment)"
default:
com = fmt.Sprintf(" (%d comments)", i.Comments)
}
return fmt.Sprintf("%s%s\n%s", i.Title, com, i.URL)
}
// Get fetches the most recent Items posted to the specified subreddit
func Get(reddit string) ([]Item, error) {
url := fmt.Sprintf("http://reddit.com/r/%s.json", reddit)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(resp.Status)
}
r := new(response)
err = json.NewDecoder(resp.Body).Decode(r)
if err != nil {
return nil, err
}
items := make([]Item, len(r.Data.Children))
for i, child := range r.Data.Children {
items[i] = child.Data
}
return items, nil
}