-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgag9.go
109 lines (89 loc) · 1.74 KB
/
gag9.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
102
103
104
105
106
107
108
109
package gag9
import (
"fmt"
"io"
"log"
"net/http"
"strings"
"golang.org/x/net/html"
)
const (
GAG9_URL = "https://9gag.com"
IMG_URL = "https://img-9gag-fun.9cache.com/photo/%s_460s.jpg"
ANCHOR_TAG = "a"
)
type Meme struct {
Description string
Image string
}
type Gag9 struct {
client *http.Client
}
func New() *Gag9 {
gag9 := &Gag9{
client: &http.Client{},
}
return gag9
}
func (g *Gag9) Find() []Meme {
req, err := http.NewRequest("GET", GAG9_URL, nil)
if err != nil {
log.Fatal(err)
}
resp, err := g.client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
return crawl(resp.Body)
}
func (g *Gag9) FindByTag(tag string) []Meme {
req, err := http.NewRequest("GET", GAG9_URL+"/tag/"+tag, nil)
if err != nil {
log.Fatal(err)
}
resp, err := g.client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
return crawl(resp.Body)
}
func crawl(body io.Reader) []Meme {
memes := make([]Meme, 0)
tokenizer := html.NewTokenizer(body)
found := false
content := ""
meme := Meme{}
for {
token := tokenizer.Next()
switch token {
case html.ErrorToken:
return memes
case html.StartTagToken:
t := tokenizer.Token()
if t.Data == ANCHOR_TAG {
for _, attr := range t.Attr {
if attr.Key == "class" && attr.Val == "badge-evt badge-track" {
img := fmt.Sprintf(IMG_URL, t.Attr[3].Val)
meme.Image = img
found = true
}
}
}
case html.TextToken:
if found {
t := tokenizer.Token()
content = content + t.String()
}
case html.EndTagToken:
t := tokenizer.Token()
if t.Data == ANCHOR_TAG && found {
meme.Description = strings.TrimSpace(content)
memes = append(memes, meme)
content = ""
found = false
}
}
}
}