-
Notifications
You must be signed in to change notification settings - Fork 1
/
find_og_tag.go
65 lines (58 loc) · 1.26 KB
/
find_og_tag.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
// functions to parse html webpage and get a url
package main
import (
"errors"
"io"
"golang.org/x/net/html"
)
func NextMetaTag(tok *html.Tokenizer) (html.Token, error) {
for {
tt := tok.Next()
switch tt {
case html.ErrorToken:
return html.Token{}, tok.Err()
case html.SelfClosingTagToken, html.StartTagToken:
token := tok.Token()
if token.Data == "meta" {
return token, nil
}
if token.Data == "body" {
return token, io.EOF
}
default:
continue
}
}
}
func AttrValue(token html.Token, ns, key string) string {
for _, attr := range token.Attr {
if attr.Namespace == ns && attr.Key == key {
return attr.Val
}
}
return ""
}
// ogType can be "video", "image", or "any"
func GetOgUrl(source io.Reader) (string, error) {
tokenizer := html.NewTokenizer(source)
reqProp := "og:" + options.OgType
if options.OgType == "any" {
reqProp = "og:video"
}
for {
metaTag, err := NextMetaTag(tokenizer)
if err == io.EOF {
return "", nil
}
// unknown error
if err != nil {
return "", errors.New("Error Parsing HTML" + err.Error())
}
prop := AttrValue(metaTag, "", "property")
if prop == reqProp ||
prop == "og:image" && options.OgType == "any" {
link := AttrValue(metaTag, "", "content")
return link, nil
}
}
}