-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
52 lines (45 loc) · 1.34 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
package main
import (
"context"
"embed"
"fmt"
"grafikart/boilerplate/server"
"io/fs"
"log"
"net/http"
)
//go:embed all:public
var assets embed.FS
func main() {
publicFS, err := fs.Sub(assets, "public")
if err != nil {
panic(fmt.Sprintf("Cannot sub public directory from %v", err))
}
viteAssets := server.NewViteAssets(publicFS)
frontMiddleware := createFrontEndMiddleware(*viteAssets)
publicServer := http.FileServer(http.FS(publicFS))
// Static Assets
http.HandleFunc("/sse", server.SSEHandler)
http.HandleFunc("/assets/", viteAssets.ServeAssets)
// FrontEnd URLs
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Serve the root
if r.URL.Path == "/" {
frontMiddleware(server.HomeHandler)(w, r)
return
}
// Otherwise serve public files
publicServer.ServeHTTP(w, r)
})
fmt.Println("Server is running on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func createFrontEndMiddleware(vite server.ViteAssets) func(func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
html := vite.GetHeadHTML()
return func(next func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "assets", html)
next(w, r.WithContext(ctx))
}
}
}