-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
65 lines (54 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
package main
import (
"bytes"
"embed"
"flag"
"fmt"
"io/fs"
"log"
"net/http"
"time"
)
//go:embed published
var staticFiles embed.FS
// Allow paths to render the default index.html
// for SPA-behavior that enables directly visiting URL paths
var allowedPathsForSPA []string
func setupServer() {
// Set up API routes
customizations()
// Create a filesystem subtree'd within /published,
// which contains the static assets embedded within the program at compile time
publishedFS, err := fs.Sub(staticFiles, "published")
if err != nil {
log.Fatal("failed to create sub file system:", err)
}
// Grab the contents for index.html
// This is a special case because we want to serve this file
// as the catch-all for other routes, so we'll need its bytes for serving later
indexHTMLContent, err := fs.ReadFile(publishedFS, "index.html")
if err != nil {
log.Fatal("failed to read index.html:", err)
}
lastModified := time.Now() // Use boot time as the index.html's last modified time since it's embedded within the binary and won't change
http.Handle("GET /", http.FileServerFS(publishedFS))
// Allow index.html to be served to get SPA-behavior
// where certain allowed URL paths can be directly visited and not 404
for _, path := range allowedPathsForSPA {
p := path
http.HandleFunc(fmt.Sprintf("GET %s", p), func(w http.ResponseWriter, r *http.Request) {
reader := bytes.NewReader(indexHTMLContent)
http.ServeContent(w, r, "index.html", lastModified, reader)
})
}
}
func main() {
setupServer()
var serverAddress string
flag.StringVar(&serverAddress, "addr", "127.0.0.1:8080", "HTTP server address")
flag.Parse()
log.Printf("Server started on http://%s", serverAddress)
if err := http.ListenAndServe(serverAddress, nil); err != nil {
log.Fatal(err)
}
}