aboutsummaryrefslogtreecommitdiffstats
path: root/web/web.go
blob: d823d464d037a61289b106b07ef1b33a5a125e94 (plain)
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
package web

import (
	"embed"
	"io/fs"
	"net/http"
	"regexp"
)

//go:generate npm install
//go:generate npm run generate

//go:embed all:.output/public
var fsys embed.FS
var urlFileRegexp = regexp.MustCompile(`[\w\-/]+\.[a-zA-Z]+$`)

type WebFileServer struct {
	root    fs.FS
	handler http.Handler
}

func NewWebFileServer() *WebFileServer {
	fsys, _ := fs.Sub(fsys, ".output/public")
	return &WebFileServer{
		root:    fsys,
		handler: http.FileServerFS(fsys),
	}
}

func (fs *WebFileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if p := r.URL.Path; p != "/" && !urlFileRegexp.MatchString(p) {
		http.ServeFileFS(w, r, fs.root, "index.html")
		return
	}
	fs.handler.ServeHTTP(w, r)
}