-
Notifications
You must be signed in to change notification settings - Fork 2
/
favicon.go
52 lines (49 loc) · 1.05 KB
/
favicon.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
package unfurlist
import (
"bytes"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
"golang.org/x/net/html/charset"
)
// extractFaviconLink parses html data in search of the first <link rel="icon"
// ...> element and returns value of its href attribute.
func extractFaviconLink(htmlBody []byte, ct string) string {
bodyReader, err := charset.NewReader(bytes.NewReader(htmlBody), ct)
if err != nil {
return ""
}
z := html.NewTokenizer(bodyReader)
tokenize:
for {
tt := z.Next()
switch tt {
case html.ErrorToken:
return ""
case html.StartTagToken:
name, hasAttr := z.TagName()
switch atom.Lookup(name) {
case atom.Body:
return ""
case atom.Link:
var href string
var isIconLink bool
for hasAttr {
var k, v []byte
k, v, hasAttr = z.TagAttr()
switch string(k) {
case "rel":
if !bytes.EqualFold(v, []byte("icon")) {
continue tokenize
}
isIconLink = true
case "href":
href = string(v)
}
}
if isIconLink && href != "" {
return href
}
}
}
}
}