This repository has been archived by the owner on Dec 4, 2021. It is now read-only.
/
rule34.go
85 lines (67 loc) · 1.93 KB
/
rule34.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
package utils
import (
"context"
"encoding/xml"
"net/http"
"strconv"
"strings"
)
var rule34Url string = "http://rule34.paheal.net/api/danbooru/find_posts/index.xml"
var httpClient *http.Client = http.DefaultClient
type Rule34Posts struct {
XMLName xml.Name `xml:"posts"`
Count string `xml:"count,attr"`
Offset string `xml:"offset,attr"`
Tags []Rule34Tag `xml:"tag"`
}
type Rule34Tag struct {
XMLName xml.Name `xml:"tag"`
ID string `xml:"id,attr"`
MD5 string `xml:"md5,attr"`
FileName string `xml:"file_name,attr"`
FileUrl string `xml:"file_url,attr"`
Height string `xml:"height,attr"`
Width string `xml:"width,attr"`
PreviewHeight string `xml:"preview_height,attr"`
PreviewWidth string `xml:"preview_width,attr"`
Rating string `xml:"rating,attr"`
Date string `xml:"date,attr"`
Tags string `xml:"tags,attr"`
Source string `xml:"source,attr"`
Score string `xml:"score,attr"`
Author string `xml:"author,attr"`
}
func GetRule34UrlImageFromTags(tags []string, limit int) (urls []string, err error) {
pureUrl := pureRule34Url(tags, limit)
request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, pureUrl, nil)
if err != nil {
return
}
response, err := httpClient.Do(request)
if err != nil {
return
}
defer response.Body.Close()
decoder := xml.NewDecoder(response.Body)
var posts *Rule34Posts
err = decoder.Decode(&posts)
if err != nil {
return
}
if posts == nil || len(posts.Tags) == 0 {
return
}
urls = make([]string, 0)
for _, tag := range posts.Tags {
urls = append(urls, tag.FileUrl)
}
return
}
func pureRule34Url(tags []string, limit int) string {
pureUrl := []byte(rule34Url)
pureUrl = append(pureUrl, "?tags="...)
pureUrl = append(pureUrl, strings.Join(tags, "%20")...)
pureUrl = append(pureUrl, "&limit="...)
pureUrl = append(pureUrl, strconv.Itoa(limit)...)
return string(pureUrl)
}