-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhandler.go
241 lines (217 loc) · 6.88 KB
/
handler.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package docsite
import (
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
)
// Handler returns an http.Handler that serves the site.
func (s *Site) Handler() http.Handler {
m := http.NewServeMux()
const (
cacheMaxAge0 = "max-age=0"
cacheMaxAgeShort = "max-age=60"
cacheMaxAgeLong = "max-age=300"
)
isNoCacheRequest := func(r *http.Request) bool {
return r.Header.Get("Cache-Control") == "no-cache"
}
isRedirect := func(path string) *url.URL {
requestPathWithLeadingSlash := path
if !strings.HasPrefix(requestPathWithLeadingSlash, "/") {
requestPathWithLeadingSlash = "/" + requestPathWithLeadingSlash
}
if redirectTo, ok := s.Redirects[requestPathWithLeadingSlash]; ok {
return redirectTo
}
return nil
}
setCacheControl := func(w http.ResponseWriter, r *http.Request, cacheControl string) {
if isNoCacheRequest(r) {
w.Header().Set("Cache-Control", cacheMaxAge0)
} else {
w.Header().Set("Cache-Control", cacheControl)
}
}
// Serve assets using http.FileServer.
if s.AssetsBase != nil {
assets, err := s.GetResources("assets", "")
if err != nil {
panic("failed to open assets: " + err.Error())
}
assetsFileServer := http.FileServer(assets)
m.Handle(s.AssetsBase.Path, http.StripPrefix(s.AssetsBase.Path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.RawQuery != "" {
versionAssets, err := s.GetResources("assets", r.URL.RawQuery)
if err != nil {
http.Error(w, "version assets error: "+err.Error(), http.StatusInternalServerError)
return
}
assetsFileServer = http.FileServer(versionAssets)
}
setCacheControl(w, r, cacheMaxAgeLong)
assetsFileServer.ServeHTTP(w, r)
})))
}
var basePath string
if s.Base != nil {
basePath = s.Base.Path
} else {
basePath = "/"
}
// Serve search.
m.Handle(path.Join(basePath, "search"), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "HEAD" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
queryStr := r.URL.Query().Get("q")
contentVersion := r.URL.Query().Get("v")
result, err := s.Search(r.Context(), contentVersion, queryStr)
if err != nil {
w.Header().Set("Cache-Control", cacheMaxAge0)
http.Error(w, "search error: "+err.Error(), http.StatusInternalServerError)
return
}
var respData []byte
if r.Method == "GET" {
respData, err = s.renderSearchPage(contentVersion, queryStr, result)
if err != nil {
w.Header().Set("Cache-Control", cacheMaxAge0)
http.Error(w, "template error: "+err.Error(), http.StatusInternalServerError)
return
}
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
setCacheControl(w, r, cacheMaxAgeShort)
if r.Method == "GET" {
_, _ = w.Write(respData)
}
}))
// Serve content.
m.Handle(basePath, http.StripPrefix(basePath, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "HEAD" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if redirectTo := isRedirect(r.URL.Path); redirectTo != nil {
http.Redirect(w, r, redirectTo.String(), http.StatusPermanentRedirect)
return
}
// Support requests for other versions of content.
var contentVersion string
if strings.HasPrefix(r.URL.Path, "@") {
end := strings.Index(r.URL.Path[1:], "/")
var urlPath string
if end == -1 {
urlPath = ""
contentVersion = r.URL.Path[1:]
} else {
urlPath = r.URL.Path[1+end+1:]
contentVersion = r.URL.Path[1 : 1+end]
}
r = requestShallowCopyWithURLPath(r, urlPath)
}
if IsContentAsset(r.URL.Path) {
// Serve non-Markdown content files (such as images) using http.FileServer.
content, err := s.Content.OpenVersion(r.Context(), contentVersion)
if err != nil {
w.Header().Set("Cache-Control", cacheMaxAge0)
if os.IsNotExist(err) {
http.Error(w, "content version not found", http.StatusNotFound)
} else {
http.Error(w, "content version error: "+err.Error(), http.StatusInternalServerError)
}
return
}
setCacheControl(w, r, cacheMaxAgeLong)
http.FileServer(content).ServeHTTP(w, r)
return
}
data := PageData{
ContentVersion: contentVersion,
ContentPagePath: r.URL.Path,
}
content, err := s.Content.OpenVersion(r.Context(), contentVersion)
if err != nil {
// Version not found.
if !os.IsNotExist(err) {
w.Header().Set("Cache-Control", cacheMaxAge0)
http.Error(w, "content version error: "+err.Error(), http.StatusNotFound)
return
}
data.ContentVersionNotFoundError = true
} else {
// Version found.
filePath, fileData, err := resolveAndReadAll(content, r.URL.Path)
if err == nil {
// Strip trailing slashes for consistency.
if strings.HasSuffix(r.URL.Path, "/") {
http.Redirect(w, r, path.Join(basePath, strings.TrimSuffix(r.URL.Path, "/")), http.StatusMovedPermanently)
return
}
// Content page found.
data.Content, err = s.newContentPage(filePath, fileData, contentVersion)
}
if err != nil {
// Content page not found.
if !os.IsNotExist(err) {
w.Header().Set("Cache-Control", cacheMaxAge0)
http.Error(w, "content error: "+err.Error(), http.StatusInternalServerError)
return
}
// If this is a versioned request, let's see if we have a
// redirect that would have matched an unversioned request. We
// can't really make this worse, after all, and we now have the
// version cached.
if contentVersion != "" {
if to := isRedirect(r.URL.Path); to != nil {
// We need to ensure we redirect to a page on the same
// version, and this needs to be an absolute path, so we
// prepend a slash.
http.Redirect(w, r, "/"+filepath.Join("@"+contentVersion, to.String()), http.StatusPermanentRedirect)
return
}
}
data.ContentPageNotFoundError = true
}
}
var respData []byte
if r.Method == "GET" {
var err error
respData, err = s.RenderContentPage(&data)
if err != nil {
w.Header().Set("Cache-Control", cacheMaxAge0)
http.Error(w, "template error: "+err.Error(), http.StatusInternalServerError)
return
}
}
// Don't cache errors; do cache on success.
if data.Content == nil {
w.WriteHeader(http.StatusNotFound)
w.Header().Set("Cache-Control", cacheMaxAge0)
} else {
setCacheControl(w, r, cacheMaxAgeShort)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if r.Method == "GET" {
_, _ = w.Write(respData)
}
})))
return m
}
func requestShallowCopyWithURLPath(r *http.Request, path string) *http.Request {
r2 := new(http.Request)
*r2 = *r
r2.URL = new(url.URL)
*r2.URL = *r.URL
r2.URL.Path = path
return r2
}
// IsContentAsset reports whether the file in the site contents file system is a content asset
// (i.e., not a Markdown file). It typically matches .png, .gif, and .svg files.
func IsContentAsset(urlPath string) bool {
return filepath.Ext(urlPath) != "" && !isContentPage(urlPath)
}