forked from tampajohn/goprerender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prerender.go
220 lines (185 loc) · 5.57 KB
/
prerender.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// Package prerender provides a Prerender.io handler implementation and a
// Negroni middleware.
package prerender
import (
"compress/gzip"
"io"
"net/http"
"net/url"
"os"
"regexp"
"strings"
e "github.com/jqatampa/gadget-arm/errors"
"google.golang.org/appengine"
"google.golang.org/appengine/urlfetch"
)
// Options provides you with the ability to specify a custom Prerender.io URL
// as well as a Prerender.io Token to include as an X-Prerender-Token header
// to the upstream server.
type Options struct {
PrerenderURL *url.URL
Token string
BlackList []regexp.Regexp
WhiteList []regexp.Regexp
UsingAppEngine bool
}
// NewOptions generates a default Options struct pointing to the Prerender.io
// service, obtaining a Token from the environment variable PRERENDER_TOKEN.
// No blacklist/whitelist is created.
func NewOptions() *Options {
url, _ := url.Parse("https://service.prerender.io/")
return &Options{
PrerenderURL: url,
Token: os.Getenv("PRERENDER_TOKEN"),
BlackList: nil,
WhiteList: nil,
UsingAppEngine: false,
}
}
// Prerender exposes methods to validate and serve content from a Prerender.io
// upstream server.
type Prerender struct {
Options *Options
}
// NewPrerender generates a new Prerender instance.
func (o *Options) NewPrerender() *Prerender {
return &Prerender{Options: o}
}
// ServeHTTP allows Prerender to act as a Negroni middleware.
func (p *Prerender) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if p.ShouldPrerender(r) {
p.PreRenderHandler(rw, r)
} else if next != nil {
next(rw, r)
}
}
// ShouldPrerender analyzes the request to determine whether it should be routed
// to a Prerender.io upstream server.
func (p *Prerender) ShouldPrerender(or *http.Request) bool {
userAgent := strings.ToLower(or.Header.Get("User-Agent"))
bufferAgent := or.Header.Get("X-Bufferbot")
isRequestingPrerenderedPage := false
reqURL := strings.ToLower(or.URL.String())
// No user agent, don't prerender
if userAgent == "" {
return false
}
// Not a GET or HEAD request, don't prerender
if or.Method != "GET" && or.Method != "HEAD" {
return false
}
// Static resource, don't prerender
for _, extension := range skippedTypes {
if strings.HasSuffix(reqURL, strings.ToLower(extension)) {
return false
}
}
// Buffer Agent or requesting an excaped fragment, request prerender
if _, ok := or.URL.Query()["_escaped_fragment_"]; bufferAgent != "" || ok {
isRequestingPrerenderedPage = true
}
// Cralwer, request prerender
for _, crawlerAgent := range crawlerUserAgents {
if strings.Contains(crawlerAgent, strings.ToLower(userAgent)) {
isRequestingPrerenderedPage = true
break
}
}
// If it's a bot/crawler/escaped fragment request apply Blacklist/Whitelist logic
if isRequestingPrerenderedPage {
if p.Options.WhiteList != nil {
matchFound := false
for _, val := range p.Options.WhiteList {
if val.MatchString(reqURL) {
matchFound = true
break
}
}
if !matchFound {
return false
}
}
if p.Options.BlackList != nil {
matchFound := false
for _, val := range p.Options.BlackList {
if val.MatchString(reqURL) {
matchFound = true
break
}
}
if matchFound {
return false
}
}
}
return isRequestingPrerenderedPage
}
func (p *Prerender) buildURL(or *http.Request) string {
url := p.Options.PrerenderURL
if !strings.HasSuffix(url.String(), "/") {
url.Path = url.Path + "/"
}
var protocol = or.URL.Scheme
if cf := or.Header.Get("CF-Visitor"); cf != "" {
match := cfSchemeRegex.FindStringSubmatch(cf)
if len(match) > 1 {
protocol = match[1]
}
}
if len(protocol) == 0 {
protocol = "http"
}
if fp := or.Header.Get("X-Forwarded-Proto"); fp != "" {
protocol = strings.Split(fp, ",")[0]
}
apiURL := url.String() + protocol + "://" + or.Host + or.URL.Path + "?" +
or.URL.RawQuery
return apiURL
}
// PreRenderHandler is a net/http compatible handler that proxies a request to
// the configured Prerender.io URL. All upstream requests are made with an
// Accept-Encoding=gzip header. Responses are provided either uncompressed or
// gzip compressed based on the downstream requests Accept-Encoding header
func (p *Prerender) PreRenderHandler(rw http.ResponseWriter, or *http.Request) {
client := &http.Client{}
req, err := http.NewRequest("GET", p.buildURL(or), nil)
e.Check(err)
if p.Options.Token != "" {
req.Header.Set("X-Prerender-Token", p.Options.Token)
}
req.Header.Set("User-Agent", or.Header.Get("User-Agent"))
req.Header.Set("Content-Type", or.Header.Get("Content-Type"))
req.Header.Set("Accept-Encoding", "gzip")
if p.Options.UsingAppEngine {
ctx := appengine.NewContext(or)
client = urlfetch.Client(ctx)
}
res, err := client.Do(req)
e.Check(err)
rw.Header().Set("Content-Type", res.Header.Get("Content-Type"))
defer res.Body.Close()
//Figure out whether the client accepts gzip responses
doGzip := strings.Contains(or.Header.Get("Accept-Encoding"), "gzip")
isGzip := strings.Contains(res.Header.Get("Content-Encoding"), "gzip")
if doGzip && !isGzip {
// gzip raw response
rw.Header().Set("Content-Encoding", "gzip")
rw.WriteHeader(res.StatusCode)
gz := gzip.NewWriter(rw)
defer gz.Close()
io.Copy(gz, res.Body)
gz.Flush()
} else if !doGzip && isGzip {
rw.WriteHeader(res.StatusCode)
// gunzip response
gz, err := gzip.NewReader(res.Body)
e.Check(err)
defer gz.Close()
io.Copy(rw, gz)
} else {
// Pass through, gzip/gzip or raw/raw
rw.Header().Set("Content-Encoding", res.Header.Get("Content-Encoding"))
rw.WriteHeader(res.StatusCode)
io.Copy(rw, res.Body)
}
}