-
Notifications
You must be signed in to change notification settings - Fork 0
/
static_serving.go
42 lines (39 loc) · 1.02 KB
/
static_serving.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
package routex
import (
"net/http"
"os"
"strings"
)
func staticServing(path string, rt *StaticRouteConfig, w http.ResponseWriter) {
// making urlpath ready to be partially substituted by the root of the file directory
path = strings.TrimRight(path, "/")
path = path + "/"
path = strings.TrimLeft(path, "/")
if strings.Contains(path, "/") {
//substitution
path = path[strings.Index(path, "/")+1:]
}
// preparing file directory path
rt.dirpath = strings.TrimRight(rt.dirpath, "/")
// building file path to open
path = rt.dirpath + "/" + path
//removing trailing slash for opening and serving a static file
path = strings.TrimRight(path, "/")
if file, err := os.ReadFile(path); err != nil {
if rt.indexFile == "" {
if file, err = os.ReadFile(path + "/" + "index.html"); err != nil {
w.Write([]byte(""))
} else {
w.Write(file)
}
} else {
if file, err = os.ReadFile(path + "/" + rt.indexFile); err != nil {
w.Write([]byte(""))
} else {
w.Write(file)
}
}
} else {
w.Write(file)
}
}