-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
76 lines (62 loc) · 1.76 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
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"embed"
"flag"
"fmt"
"io/fs"
"log"
"net/http"
"regexp"
"strings"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/cors"
)
var (
flagHost string
)
//go:embed all:build
var websiteStatic embed.FS
func init() {
flag.StringVar(&flagHost, "host", ":8080", "Set the host what the service listening on")
flag.Parse()
}
func main() {
router := chi.NewRouter()
cors := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300,
})
router.Use(cors.Handler)
router.Use(middleware.Compress(5))
clientDirectory, err := fs.Sub(websiteStatic, "build")
if err != nil {
log.Print("fs.Sub: ", err.Error())
}
siteHandler := fileServerExtension(http.FileServer(http.FS(clientDirectory)))
router.Get("/*", serveDir(http.StripPrefix("/", siteHandler)))
router.Head("/*", serveDir(http.StripPrefix("/", siteHandler)))
fmt.Println("Server listening on port ", flagHost)
if err := http.ListenAndServe(flagHost, router); err != nil {
panic(err)
}
}
func serveDir(handler http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler.ServeHTTP(w, r)
})
}
func fileServerExtension(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Add Cache-Control to the response
rc, _ := regexp.Compile("(.svg|.png|.jpg|.jpeg|.js|.css|.woff|.woff2|.ico|.txt)")
if !rc.MatchString(r.URL.Path) && !strings.HasSuffix(r.URL.Path, "/") {
r.URL.Path = r.URL.Path + "/"
}
h.ServeHTTP(w, r)
}
}