aboutsummaryrefslogtreecommitdiff
path: root/backend
diff options
context:
space:
mode:
Diffstat (limited to 'backend')
-rw-r--r--backend/config.go3
-rw-r--r--backend/router.go45
2 files changed, 48 insertions, 0 deletions
diff --git a/backend/config.go b/backend/config.go
new file mode 100644
index 0000000..b7624fd
--- /dev/null
+++ b/backend/config.go
@@ -0,0 +1,3 @@
+package backend
+
+type Config struct{}
diff --git a/backend/router.go b/backend/router.go
index 6c7f9f8..4c3b2f8 100644
--- a/backend/router.go
+++ b/backend/router.go
@@ -1,7 +1,10 @@
package backend
import (
+ "embed"
+ "io/fs"
"net/http"
+ "strings"
"time"
"github.com/go-chi/chi/v5"
@@ -22,3 +25,45 @@ func NewRouter() *chi.Mux {
})
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, r *http.Request) {
+ ctx := chi.RouteContext(r.Context())
+ pathPrefix := strings.TrimSuffix(ctx.RoutePattern(), "/*")
+ http.StripPrefix(pathPrefix, http.FileServerFS(root)).ServeHTTP(w, r)
+ })
+}