-
Notifications
You must be signed in to change notification settings - Fork 7
/
handler.go
202 lines (183 loc) · 5.57 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
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=3600"
)
isNoCacheRequest := func(r *http.Request) bool {
return r.Header.Get("Cache-Control") == "no-cache"
}
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 {
assetsFileServer := http.FileServer(s.Assets)
m.Handle(s.AssetsBase.Path, http.StripPrefix(s.AssetsBase.Path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
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(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
}
{
requestPathWithLeadingSlash := r.URL.Path
if !strings.HasPrefix(requestPathWithLeadingSlash, "/") {
requestPathWithLeadingSlash = "/" + requestPathWithLeadingSlash
}
if redirectTo, ok := s.Redirects[requestPathWithLeadingSlash]; ok {
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.StatusInternalServerError)
return
}
data.ContentVersionNotFoundError = true
} else {
// Version found.
filePath, fileData, err := resolveAndReadAll(content, r.URL.Path)
if err == nil {
// Content page found.
data.Content, err = s.newContentPage(r.Context(), 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
}
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)
}