-
Notifications
You must be signed in to change notification settings - Fork 0
/
GetDescription.go
53 lines (45 loc) · 1.56 KB
/
GetDescription.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
package katsuragi
import (
"fmt"
"golang.org/x/net/html"
)
func (f *Fetcher) GetDescription(url string) (string, error) {
html, err := retrieveHTML(url, f)
if err != nil {
return "", err
}
description, found := traverseAndExtractDescription(html)
if !found {
return "", fmt.Errorf("GetDescription failed to find description in HTML")
}
return description, nil
}
// Predefined sets of valid `name` and `property` values
var validDescriptionMeta = map[string]bool{
"description": true,
"twitter:description": true,
"og:description": true,
}
// traverseAndExtractDescription traverses the HTML node tree and extracts description content
func traverseAndExtractDescription(n *html.Node) (string, bool) {
if n.Type == html.ElementNode {
if n.Data == "meta" {
attrMap := extractAttributes(n.Attr) // Extract attributes to map
if name, found := attrMap["name"]; found && validDescriptionMeta[name] {
if content, found := attrMap["content"]; found && content != "" {
return content, true
}
} else if property, found := attrMap["property"]; found && validDescriptionMeta[property] {
if content, found := attrMap["content"]; found && content != "" {
return content, true
}
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if description, found := traverseAndExtractDescription(c); found {
return description, true
}
}
return "", false
}