-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhtml_ajax.go
87 lines (77 loc) · 1.76 KB
/
html_ajax.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
package main
import (
"bytes"
"net/url"
"strings"
"golang.org/x/net/html/atom"
"golang.org/x/net/html"
)
const escapedFragment = "_escaped_fragment_"
// This file implements Ajax Crawling according to:
// https://developers.google.com/webmasters/ajax-crawling/docs/specification
func escapeFragment(rawurl string) string {
u, err := url.Parse(rawurl)
if err != nil || !strings.HasPrefix(u.Fragment, "!") {
return rawurl
}
q := u.Query()
q.Set(escapedFragment, u.Fragment[1:])
u.RawQuery = q.Encode()
u.Fragment = ""
return u.String()
}
func unescapeFragment(rawurl string) string {
u, err := url.Parse(rawurl)
if err != nil {
return rawurl
}
q := u.Query()
fragment := q.Get(escapedFragment)
q.Del(escapedFragment)
u.RawQuery = q.Encode()
if fragment != "" {
u.Fragment = "!" + fragment
}
return u.String()
}
func escapeFragmentMeta(rawurl string, content []byte) (newurl string, escaped bool) {
u, err := url.Parse(rawurl)
if err != nil {
return
}
q := u.Query()
if _, ok := q[escapedFragment]; ok {
return
}
// let's parse this document and find the fragment meta
tokenizer := html.NewTokenizer(bytes.NewReader(content))
for {
tt := tokenizer.Next()
switch tt {
case html.ErrorToken:
return
case html.SelfClosingTagToken:
t := tokenizer.Token()
if t.DataAtom == atom.Meta {
var name, content string
for _, attr := range t.Attr {
switch attr.Key {
case "name":
name = attr.Val
case "content":
content = attr.Val
}
}
if name == "fragment" && strings.HasPrefix(content, "!") {
q.Set(escapedFragment, content[1:])
u.RawQuery = q.Encode()
return u.String(), true
}
}
case html.StartTagToken:
if tokenizer.Token().DataAtom == atom.Body {
return
}
}
}
}