-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
63 lines (46 loc) · 1.28 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
package main
import (
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"gofr.dev/pkg/gofr"
)
const defaultStaticFilePath = `./static`
const indexHTML = "/index.html"
const htmlExtension = ".html"
const rootPath = "/"
func main() {
app := gofr.New()
staticFilePath := app.Config.GetOrDefault("STATIC_DIR_PATH", defaultStaticFilePath)
app.UseMiddleware(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/.well-known/") {
h.ServeHTTP(w, r)
return
}
filePath := filepath.Join(staticFilePath, r.URL.Path)
// check if the path has a file extension
ok, _ := regexp.MatchString(`\.\S+$`, filePath)
if r.URL.Path == rootPath {
filePath += indexHTML
} else if !ok {
if _, err := os.Stat(filePath + ".html"); err == nil {
filePath += htmlExtension
} else if stat, err := os.Stat(filePath); err == nil && stat.IsDir() {
filePath += indexHTML
}
}
if _, err := os.Stat(filePath); os.IsNotExist(err) {
w.WriteHeader(http.StatusNotFound)
filePath = filepath.Join(staticFilePath, "404.html")
http.ServeFile(w, r, filePath)
return
}
http.ServeFile(w, r, filePath)
})
})
app.AddStaticFiles("/", staticFilePath)
app.Run()
}