/
boilerplate.go
86 lines (72 loc) · 1.98 KB
/
boilerplate.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
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"path"
"strings"
)
type StaticHandler struct {
http.Dir
}
func serveStaticFilesOr404(responseWriter http.ResponseWriter, request *http.Request) {
staticHandler := StaticHandler{http.Dir(webRoot)}
staticHandler.ServeHttp(responseWriter, request)
}
func serve404OnErr(err error, responseWriter http.ResponseWriter) bool {
if err != nil {
serve404(responseWriter)
return true
}
return false
}
func serve404(responseWriter http.ResponseWriter) {
responseWriter.WriteHeader(http.StatusNotFound)
template, err := ioutil.ReadFile(webRoot + "/error-templates/404.html")
if err != nil {
template = []byte("Error 404 - Page Not Found. Additionally a 404 page template could not be found.")
}
fmt.Fprint(responseWriter, string(template))
}
func (sh *StaticHandler) ServeHttp(responseWriter http.ResponseWriter, request *http.Request) {
staticFilePath := staticFilePath(request)
fileHandle, error := sh.Open(staticFilePath)
if serve404OnErr(error, responseWriter) {
return
}
defer fileHandle.Close()
fileInfo, error := fileHandle.Stat()
if serve404OnErr(error, responseWriter) {
return
}
if fileInfo.IsDir() {
if request.URL.Path[len(request.URL.Path)-1] != '/' {
http.Redirect(responseWriter, request, request.URL.Path+"/", http.StatusFound)
return
}
fileHandle, error = sh.Open(staticFilePath + "/index.html")
if serve404OnErr(error, responseWriter) {
return
}
defer fileHandle.Close()
fileInfo, error = fileHandle.Stat()
if serve404OnErr(error, responseWriter) {
return
}
}
http.ServeContent(responseWriter, request, fileInfo.Name(), fileInfo.ModTime(), fileHandle)
}
func staticFilePath(request *http.Request) string {
staticFilePath := request.URL.Path
if !strings.HasPrefix(staticFilePath, "/") {
staticFilePath = "/" + staticFilePath
request.URL.Path = staticFilePath
}
return path.Clean(staticFilePath)
}
func panicOnError(error error) {
if error != nil {
log.Panic(error)
}
}