-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
80 lines (66 loc) · 1.87 KB
/
main.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
// Copyright 2023 Maxime Malgorn. All rights reserved.
// Use of this source code is governed by a MIT-style.
// The license can be found in the LICENSE file.
package main
import (
"log"
"net/http"
"strconv"
"strings"
)
func LogRequest(r *http.Request) {
if enableLogging {
log.Println(r.Method, r.URL.Path)
}
}
func ApplyCorsPolicy(origin string, w http.ResponseWriter) {
if origin != "" && len(allowOriginList) > 0 {
for _, allowedOrigin := range allowOriginList {
if allowedOrigin == origin {
w.Header().Set("Access-Control-Allow-Origin", origin)
break
}
}
}
}
func handleRequest(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// forward to https if still using http
if r.Header.Get("X-Forwarded-Proto") == "http" {
http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusMovedPermanently)
if enableLogging {
log.Println(301, r.Method, r.URL.Path)
}
return
}
// do not display directory listings
if strings.HasSuffix(r.URL.Path, "/") {
http.NotFound(w, r)
return
}
// apply CORS policy based on origin header
ApplyCorsPolicy(r.Header.Get("Origin"), w)
LogRequest(r)
h.ServeHTTP(w, r)
})
}
func main() {
Configure()
// Setup file system
var fileSystem http.FileSystem = http.Dir(basePath)
// Create file server object
handler := handleRequest(http.FileServer(fileSystem))
// Middlewares
handler = UploadMiddleware(handler)
handler = DeleteMiddleware(handler)
handler = ExposeMiddleware(handler)
handler = CachingMiddleware(handler)
handler = GzipMiddleware(handler)
// Start the server
http.Handle(pathPrefix, handler)
// Log errors if found
port := ":" + strconv.FormatInt(int64(portPtr), 10)
log.Printf("Serving directory %v", basePath)
log.Printf("Listening at 0.0.0.0%v %v...", port, pathPrefix)
log.Fatalln(http.ListenAndServe(port, nil))
}