-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdesc.go
executable file
·91 lines (72 loc) · 1.6 KB
/
desc.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
package main
import (
"log"
"net/http"
"strings"
"time"
"golang.org/x/net/html"
)
func getDescription(url string) string {
log.Println("Getting description for: " + url)
// https://www.devdungeon.com/content/web-scraping-go
// Create HTTP client with timeout
client := &http.Client{
Timeout: 5 * time.Second,
}
// Create and modify HTTP request before sending
request, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println(err)
}
request.Header.Set("User-Agent", "Alakbot v0.1 (+http://alak.bar/alakbot)")
// Make request
response, err := client.Do(request)
if err != nil {
return ""
}
defer response.Body.Close()
body := html.NewTokenizer(response.Body)
for {
tt := body.Next()
if tt == html.ErrorToken {
log.Println("HTML Error Token")
return ""
}
switch tt {
case html.ErrorToken:
continue
case html.StartTagToken, html.SelfClosingTagToken:
tag, has := body.TagName()
if !has || string(tag) != "meta" {
continue
} else {
tagStr := string(tag)
isDesc := false
var description string
for {
key, val, has := body.TagAttr()
keyStr := string(key)
valStr := string(val)
if tagStr == "meta" {
if keyStr == "name" && strings.ToLower(valStr) == "description" {
isDesc = true
} else if keyStr == "content" {
if valStr == "" {
break
} else {
firstLetter := valStr[0:1]
description = strings.Title(string(firstLetter)) + valStr[1:]
}
}
}
if !has {
break
}
}
if isDesc {
return description
}
}
}
}
}