-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler.go
More file actions
68 lines (52 loc) · 1.49 KB
/
handler.go
File metadata and controls
68 lines (52 loc) · 1.49 KB
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
package main
import (
"net/http"
"path/filepath"
"strings"
"gofr.dev/pkg/gofr/datasource/file"
)
type staticFileHandler struct {
fs file.FileSystem
staticFilePath string
spaMode bool
defaultExtension string
next http.Handler
}
func (h *staticFileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/.well-known/") {
h.next.ServeHTTP(w, r)
return
}
filePath, hasExtension := h.resolveFilePath(r.URL.Path)
if _, err := h.fs.Stat(filePath); err != nil {
if h.spaMode && !hasExtension {
http.ServeFile(w, r, filepath.Join(h.staticFilePath, indexHTML))
return
}
http.ServeFile(&statusOverrideWriter{ResponseWriter: w, status: http.StatusNotFound}, r,
filepath.Join(h.staticFilePath, "404.html"))
return
}
http.ServeFile(w, r, filePath)
}
func (h *staticFileHandler) resolveFilePath(urlPath string) (string, bool) {
filePath := filepath.Join(h.staticFilePath, urlPath)
hasExtension := filepath.Ext(filePath) != ""
if urlPath == rootPath {
filePath += indexHTML
} else if !hasExtension {
if _, err := h.fs.Stat(filePath + h.defaultExtension); err == nil {
filePath += h.defaultExtension
} else if info, err := h.fs.Stat(filePath); err == nil && info.IsDir() {
filePath += indexHTML
}
}
return filePath, hasExtension
}
type statusOverrideWriter struct {
http.ResponseWriter
status int
}
func (w *statusOverrideWriter) WriteHeader(int) {
w.ResponseWriter.WriteHeader(w.status)
}