-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http-file-server.go
63 lines (55 loc) · 1.24 KB
/
http-file-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
package main
import (
"bytes"
"log"
"net/http"
"strings"
)
type responseWriter struct {
Body bytes.Buffer
CustomHeader http.Header
StatusCode int
}
func (crw *responseWriter) Header() http.Header {
return crw.CustomHeader
}
func (crw *responseWriter) Write(b []byte) (int, error) {
return crw.Body.Write(b)
}
func (crw *responseWriter) WriteHeader(statusCode int) {
crw.StatusCode = statusCode
}
type fallbackFileServer struct {
primary http.Handler
secondary http.Handler
eTag string
}
func (s *fallbackFileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { //nolint:varnamelen
if r.Header.Get("If-None-Match") == s.eTag {
w.WriteHeader(http.StatusNotModified)
return
}
filePath := r.URL.Path
if strings.Contains(filePath, ".env") {
w.WriteHeader(http.StatusBadRequest)
return
}
rw := responseWriter{ //nolint:exhaustruct
CustomHeader: make(http.Header),
StatusCode: http.StatusOK,
}
rw.Header().Set("ETag", s.eTag)
s.primary.ServeHTTP(&rw, r)
if rw.StatusCode == http.StatusNotFound {
s.secondary.ServeHTTP(w, r)
return
}
for k, v := range rw.CustomHeader {
w.Header()[k] = v
}
w.WriteHeader(rw.StatusCode)
_, err := w.Write(rw.Body.Bytes())
if err != nil {
log.Println(err)
}
}