/
standard_meta.go
111 lines (95 loc) · 2.03 KB
/
standard_meta.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
110
111
package handlers
import (
"errors"
"golang.org/x/net/html"
"strings"
)
type StandardLinkPreview struct {
*LinkPreviewContext
}
func (p *StandardLinkPreview) Preview() (*LinkPreviewContext, error) {
err := p.request()
if nil != err {
return nil, err
}
err = p.readTags()
if nil != err {
return nil, err
}
return p.PreviewContext(), nil
}
func (p *StandardLinkPreview) readTags() error {
titleNode := p.Parsed.Find("html > head > title")
if 0 == titleNode.Length() {
return errors.New("title not found")
}
p.Title = titleNode.Text()
// Find `favicon.ico`.
linkNodes := p.Parsed.Find("html > head > link")
for _, node := range linkNodes.Nodes {
for _, attr := range node.Attr {
switch strings.ToLower(attr.Key) {
case "rel":
if attr.Val != "icon" {
break
}
p.parseFavicon(node)
default:
continue
}
}
}
// Parse <meta> tags.
metaNodes := p.Parsed.Find("html > head > meta")
for _, node := range metaNodes.Nodes {
for _, attr := range node.Attr {
switch strings.ToLower(attr.Key) {
case "property":
p.parseMetaProperties(attr.Val, node)
break
case "name":
if "description" == strings.ToLower(attr.Val) && "" == p.Description {
content := p.parseMetaContent(node)
p.Description = content
break
}
default:
continue
}
}
}
return nil
}
func (p *StandardLinkPreview) parseMetaContent(node *html.Node) string {
var content string
for _, attr := range node.Attr {
switch strings.ToLower(attr.Key) {
case "content":
content = attr.Val
break
default:
continue
}
}
return content
}
func (p *StandardLinkPreview) parseMetaProperties(nodeType string, node *html.Node) {
nodeType = strings.ToLower(nodeType)
if ! strings.HasPrefix(nodeType, "og:") {
return
}
slices := strings.Split(nodeType, ":")
if 2 != len(slices) {
return
}
nodeType = slices[1]
content := p.parseMetaContent(node)
switch nodeType {
case "description":
p.Description = content
case "image":
p.ImageURL = content
case "title":
p.Title = content
}
}