This repository has been archived by the owner on Jun 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeme.go
101 lines (87 loc) · 2.16 KB
/
meme.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
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"encoding/json"
"github.com/gin-gonic/gin"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"time"
)
var (
amount = 20
memes []gin.H
fetchedAt time.Time
)
func FetchMemes() {
fetchedAt = time.Now()
memes = make([]gin.H, 0)
fetchPart(false, "")
for i := 0; i < amount-1; i++ {
log.Printf("Fetching meme part %o/%o", i+2, amount-1)
fetchPart(false, memes[len(memes)-1]["id"].(string))
}
}
func fetchPart(first bool, after string) {
var url string
if first {
url = "https://reddit.com/u/bendimester_23/m/meme.json?sort=rising&limit=100"
} else {
url = "https://reddit.com/u/bendimester_23/m/meme.json?sort=rising&limit=100?after=" + after
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatalf("Error fetching memes!\n%s", err.Error())
}
req.Header.Set("User-Agent", "Mozilla/5.0")
res, err := new(http.Client).Do(req)
if err != nil {
log.Fatalf("Error fetching memes!\n%s", err.Error())
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(res.Body)
var data map[string]interface{}
rawData, _ := ioutil.ReadAll(res.Body)
if res.StatusCode != 200 {
log.Println(string(rawData))
log.Fatalf("Error fetching memes! Got code: %o", res.StatusCode)
}
err = json.Unmarshal(rawData, &data)
if err != nil {
log.Fatalf("Error parsing JSON.\n%s", err.Error())
}
var posts []interface{}
posts = data["data"].(map[string]interface{})["children"].([]interface{})
result := make([]gin.H, 0, 0)
for _, i := range posts {
iii := i.(map[string]interface{})["data"]
ii := iii.(map[string]interface{})
r := gin.H{
"subreddit": ii["subreddit"],
"id": ii["id"],
"image": ii["url_overridden_by_dest"],
"url": "https://reddit.com" + ii["permalink"].(string),
"author": ii["author"],
"title": ii["title"],
}
result = append(result, r)
}
memes = append(memes, result...)
}
func GetRandomMeme() gin.H {
if time.Now().Sub(fetchedAt).Hours() > 3 {
go FetchMemes()
}
return memes[rand.Intn(len(memes))]
}
func GetMemeCount() int {
return len(memes)
}
func GetAllMemes() []gin.H {
if time.Now().Sub(fetchedAt).Hours() > 3 {
go FetchMemes()
}
return memes
}