-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
62 lines (56 loc) · 1.2 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
package main
import (
"errors"
"io/fs"
"log"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Compress(5))
r.Use(middleware.RealIP)
port := ":8081"
if len(os.Args) > 1 {
port = os.Args[1]
}
fsh := http.FileServer(http.Dir("."))
r.HandleFunc("/*", func(w http.ResponseWriter, r *http.Request) {
p := path.Clean(strings.TrimPrefix(r.URL.Path, "/"))
if p == "" {
p = "index.html"
}
_, err := os.Stat(p)
if errors.Is(err, fs.ErrNotExist) {
log.Printf("404 %s %s", r.Method, r.URL.Path)
// write content of /index.html to w
// get file extension of r.URL.Path
ext := filepath.Ext(p)
if ext == ".js" {
w.Header().Set("Content-Type", "application/javascript")
return
}
if ext == ".css" {
w.Header().Set("Content-Type", "text/css")
return
}
b, err := os.ReadFile("index.html")
if err != nil {
log.Println(err)
return
}
w.Write(b)
return
}
fsh.ServeHTTP(w, r)
})
log.Printf("listening on http://localhost%s/", port)
log.Fatal(http.ListenAndServe(port, r))
}