This repository has been archived by the owner on Sep 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
70 lines (56 loc) · 1.42 KB
/
main.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
package main
import (
"encoding/json"
"io/ioutil"
"log"
"math/rand"
"net/http"
"time"
"github.com/danielchatfield/go-chalk"
)
type ShitPost struct {
Data struct {
Children []struct {
Post struct {
Title string `json:"title"`
Text string `json:"selftext"`
} `json:"data"`
} `json:"children"`
} `json:"data"`
}
func main() {
httpclient := &http.Client{}
req, err := http.NewRequest("GET", "https://www.reddit.com/r/copypasta/top/.json?sort=top&t=week&showmedia=false&mediaonly=false&is_self=true&limit=100", nil)
if err != nil {
log.Println("error:", err)
return
}
req.Header.Add("User-Agent", "Meme-cli")
res, err := httpclient.Do(req)
if err != nil {
log.Println("error:", err)
return
}
if res.StatusCode != 200 {
log.Fatalln("Non-OK Status:", res.Status)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Println("error:", err)
return
}
s, err := getData([]byte(body)) // turn the JSON response into a struct
rand.Seed(time.Now().UnixNano()) // Seed the random number
randomPost := rand.Intn(100 - 1) + 1 // TODO: make the first number (max) depend on how many "Children" structs are returned
post := s.Data.Children[randomPost].Post
log.Println(chalk.Yellow(post.Title), "\n",
chalk.Blue(post.Text))
}
func getData(body []byte) (*ShitPost, error) {
var s = new(ShitPost)
err := json.Unmarshal(body, &s)
if err != nil {
log.Println("error:", err)
}
return s, err
}