-
Notifications
You must be signed in to change notification settings - Fork 0
/
reddit.go
75 lines (66 loc) · 1.65 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"encoding/json"
"errors"
"net/http"
)
// RedditPayload json
type RedditPayload struct {
Data PayloadData
}
// PayloadData json
type PayloadData struct {
Children []PayloadDataChild
}
// PayloadDataChild json
type PayloadDataChild struct {
Data PayloadDataChildData
}
// PayloadDataChildData json
type PayloadDataChildData struct {
Preview PayloadDataChildDataPreview
Name string
URL string
}
// PayloadDataChildDataPreview json
type PayloadDataChildDataPreview struct {
Images []PayloadDataChildDataPreviewImage
}
// PayloadDataChildDataPreviewImage json
type PayloadDataChildDataPreviewImage struct {
Source PayloadDataChildDataPreviewImageSource
}
// PayloadDataChildDataPreviewImageSource json
type PayloadDataChildDataPreviewImageSource struct {
URL string
Width int
Height int
}
func getReddit(subreddit, sort string, afterID string) (result *RedditPayload, newAfterID string, err error) {
client := &http.Client{}
var url string
if afterID == "" {
url = "https://www.reddit.com/" + subreddit + "/" + sort + ".json?count=25"
} else {
url = "https://www.reddit.com/" + subreddit + "/" + sort + ".json?count=25&after=" + afterID
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, "", err
}
req.Header.Set("User-Agent", "go-reddit-wallpaper/"+version)
res, err := client.Do(req)
if err != nil {
return nil, "", err
}
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(&result)
if err != nil {
return nil, "", err
}
if len(result.Data.Children) == 0 {
return nil, "", errors.New("reach end of page limit")
}
newAfterID = result.Data.Children[0].Data.Name
return
}