/
server.go
262 lines (220 loc) · 6.16 KB
/
server.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package webserver
import (
"fmt"
log "github.com/sirupsen/logrus"
"mime"
"net/http"
"os"
"path"
"strings"
"time"
)
const DefaultPort = 80
const DefaultTLSPort = 443
type pathType int
const (
pathTypeNothing = pathType(iota)
pathTypeFile
pathTypeDirectory
)
type pathDescription struct {
pathType pathType
rawPath string
contentType *string
size *int64
lastModified *time.Time
}
type NotFoundResponseKind int
const (
NotFoundRedirect = NotFoundResponseKind(iota)
NotFoundPage
)
type NotFoundResponse struct {
Kind NotFoundResponseKind
RedirectURL string
}
func defaultNotFoundResponse(_ string) NotFoundResponse {
return NotFoundResponse{
Kind: NotFoundPage,
}
}
func readPathDescription(filePath string) pathDescription {
fileInfo, err := os.Stat(filePath)
if err != nil {
return pathDescription{
pathType: pathTypeNothing,
rawPath: filePath,
}
}
lastModified := fileInfo.ModTime()
if fileInfo.IsDir() {
return pathDescription{
pathType: pathTypeDirectory,
rawPath: filePath,
lastModified: &lastModified,
}
}
contentType := mime.TypeByExtension(path.Ext(filePath))
size := fileInfo.Size()
return pathDescription{
pathType: pathTypeFile,
rawPath: filePath,
contentType: &contentType,
size: &size,
lastModified: &lastModified,
}
}
func shouldGzipFile(description pathDescription, request *http.Request) bool {
acceptEncoding := request.Header.Get("Accept-Encoding")
if !strings.Contains(acceptEncoding, "gzip") {
return false
}
// NOTE: Don't gzip video content.
mimeType := mime.TypeByExtension(path.Ext(description.rawPath))
if len(mimeType) >= 5 && mimeType[:5] == "video" {
return false
}
return true
}
func serveFile(
response http.ResponseWriter,
request *http.Request,
description pathDescription,
gzipCache *gzipFileCache,
) {
if !shouldGzipFile(description, request) {
http.ServeFile(response, request, description.rawPath)
return
}
if err := gzipCache.serveGzipFile(response, description); err != nil {
log.WithError(err).
WithField("file", description.rawPath).
Error("Could not serve file gzipped")
http.ServeFile(response, request, description.rawPath)
}
}
func firstValidIndexPath(directoryPath string) pathDescription {
validIndexFiles := []string{
"index.html",
"index.htm",
}
for _, indexFile := range validIndexFiles {
indexPath := path.Join(directoryPath, indexFile)
description := readPathDescription(indexPath)
if description.pathType == pathTypeFile {
return description
}
}
return pathDescription{
pathType: pathTypeNothing,
}
}
func serveDirectory(
response http.ResponseWriter,
request *http.Request,
directoryPath string,
gzipCache *gzipFileCache,
) {
if description := firstValidIndexPath(directoryPath); description.pathType != pathTypeNothing {
serveFile(response, request, description, gzipCache)
return
}
http.ServeFile(response, request, directoryPath)
}
func serveURL(
response http.ResponseWriter,
request *http.Request,
url string,
config Config,
onNotFound func(string) NotFoundResponse,
gzipCache *gzipFileCache,
) {
filePath := path.Clean(path.Join(config.StaticFilesPath, url))
if !config.EnableGzip {
http.ServeFile(response, request, filePath)
return
}
description := readPathDescription(filePath)
switch description.pathType {
case pathTypeNothing:
notFoundResponse := onNotFound(url)
switch notFoundResponse.Kind {
case NotFoundPage:
http.NotFound(response, request)
case NotFoundRedirect:
serveURL(response, request, notFoundResponse.RedirectURL,
config, onNotFound, gzipCache)
}
case pathTypeFile:
serveFile(response, request, description, gzipCache)
case pathTypeDirectory:
serveDirectory(response, request, filePath, gzipCache)
}
}
func HandlerWithOnNotFound(config Config, onNotFound func(string) NotFoundResponse) http.HandlerFunc {
var gzipCache gzipFileCache
if config.EnableGzip {
gzipCache = createGzipFileCache(config.ServerName)
}
return func(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
response.Header().Set("Cross-Origin-Embedder-Policy", "require-corp")
url := request.URL.Path
log.WithField("url", url).
Trace("Got request")
serveURL(response, request, url,
config, onNotFound, &gzipCache)
}
}
func Handler(config Config) http.HandlerFunc {
return HandlerWithOnNotFound(config, defaultNotFoundResponse)
}
func displayWebAddress(address string, port uint, useTLS bool) string {
protocol := "http"
if useTLS {
protocol = "https"
}
if (useTLS && port == DefaultTLSPort) || (!useTLS && port == DefaultPort) {
return fmt.Sprintf("%s://%s", protocol, address)
} else {
return fmt.Sprintf("%s://%s:%d", protocol, address, port)
}
}
func httpToHttpsRedirectService(config Config) {
log.Info("Starting http to https redirect service")
bindAddress := fmt.Sprintf("%s:80", config.Address)
err := http.ListenAndServe(bindAddress, http.HandlerFunc(
func(response http.ResponseWriter, request *http.Request) {
redirectUrl := fmt.Sprintf("https://%s:%d%s", request.Host, config.Port, request.URL.Path)
if len(request.URL.RawQuery) > 0 {
redirectUrl = fmt.Sprintf("%s?%s", redirectUrl, request.URL.RawQuery)
}
log.WithField("url", redirectUrl).
Trace("Got http request, redirecting to https")
http.Redirect(response, request, redirectUrl, http.StatusPermanentRedirect)
}))
if err != nil {
log.Fatal(err)
}
}
func Listen(config Config, handler http.HandlerFunc) error {
useTLS := config.CertFilePath != "" && config.KeyFilePath != ""
config.log(useTLS)
bindAddress := fmt.Sprintf("%s:%d", config.Address, config.Port)
log.WithFields(log.Fields{
"address": displayWebAddress(config.Address, config.Port, useTLS),
"TLS": useTLS,
}).Info("Started listening for connections")
if useTLS {
if config.EnableHttpToHttps {
go httpToHttpsRedirectService(config)
}
return http.ListenAndServeTLS(bindAddress,
config.CertFilePath, config.KeyFilePath, handler)
} else {
if config.EnableHttpToHttps {
log.Warning("Can't enable http to https redirect, as TLS is not enabled")
}
return http.ListenAndServe(bindAddress, handler)
}
}