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
|
package backend
import (
"embed"
"io/fs"
"net/http"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
//go:embed templates
var templates embed.FS
func NewRouter() *chi.Mux {
r := chi.NewRouter()
r.Use(middleware.Timeout(30 * time.Second))
r.Use(middleware.Logger)
return r
}
// httpEmbedFS is an implementation of fs.FS, fs.ReadDirFS and fs.ReadFileFS helping to manage embed.FS for http server
type httpEmbedFS struct {
embed.FS
prefix string
}
func (h *httpEmbedFS) Open(name string) (fs.File, error) {
return h.FS.Open(h.prefix + "/" + name)
}
func (h *httpEmbedFS) ReadFile(name string) ([]byte, error) {
return h.FS.ReadFile(h.prefix + "/" + name)
}
func (h *httpEmbedFS) ReadDir(name string) ([]fs.DirEntry, error) {
return h.FS.ReadDir(h.prefix + "/" + name)
}
// UsableEmbedFS converts embed.FS into usable fs.FS by Golatt
//
// folder may not finish or start with a slash (/)
func UsableEmbedFS(folder string, em embed.FS) fs.FS {
return &httpEmbedFS{
prefix: folder,
FS: em,
}
}
func HandleStaticFiles(r *chi.Mux, path string, root fs.FS) {
if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
path += "/"
}
path += "*"
r.Get(path, func(w http.ResponseWriter, req *http.Request) {
ctx := chi.RouteContext(req.Context())
pathPrefix := strings.TrimSuffix(ctx.RoutePattern(), "/*")
if pathPrefix+"/" == req.URL.Path {
r.NotFoundHandler().ServeHTTP(w, req)
return
}
http.StripPrefix(pathPrefix, http.FileServerFS(root)).ServeHTTP(w, req)
})
}
|