all repos — searchix @ 3bbb49e74b8eab7714c2df1162d086f6d731e1e8

Search engine for NixOS, nix-darwin, home-manager and NUR users

build: optionally embed frontend files
Alan Pearce alan@alanpearce.eu
Fri, 10 May 2024 23:05:24 +0200
commit

3bbb49e74b8eab7714c2df1162d086f6d731e1e8

parent

00eb7541d54e76f8b55fe499d6955786927b207b

A frontend/dev.go
@@ -0,0 +1,9 @@+//go:build !embed
+
+package frontend
+
+import (
+	"os"
+)
+
+var Files = os.DirFS("frontend/")
A frontend/embedded.go
@@ -0,0 +1,8 @@+//go:build embed
+
+package frontend
+
+import "embed"
+
+//go:embed *
+var Files embed.FS
M internal/server/server.gointernal/server/server.go
@@ -16,6 +16,7 @@ "slices" 	"strconv"
 	"time"
 
+	"searchix/frontend"
 	cfg "searchix/internal/config"
 	"searchix/internal/importer"
 	"searchix/internal/options"
@@ -243,10 +244,7 @@ http.Error(w, err.Error(), http.StatusInternalServerError) 		}
 	})
 
-	mux.Handle(
-		"/static/",
-		http.StripPrefix("/static/", http.FileServer(http.Dir("frontend/static"))),
-	)
+	mux.Handle("/static/", http.FileServer(http.FS(frontend.Files)))
 
 	if runtimeConfig.LiveReload {
 		applyDevModeOverrides(config)
M internal/server/templates.gointernal/server/templates.go
@@ -4,9 +4,10 @@ import ( 	"fmt"
 	"html"
 	"html/template"
+	"io/fs"
 	"log/slog"
 	"path"
-	"path/filepath"
+	"searchix/frontend"
 	"searchix/internal/options"
 	"strings"
 
@@ -50,13 +51,13 @@ func loadTemplate(layoutFile string, filename string) (*template.Template, error) { 	tpl := template.New("index.gotmpl")
 
 	tpl.Funcs(templateFuncs)
-	_, err := tpl.ParseFiles(layoutFile)
+	_, err := tpl.ParseFS(frontend.Files, layoutFile)
 	if err != nil {
 		return nil, errors.WithMessage(err, "could not parse layout template")
 	}
 
 	if filename != "" {
-		_, err = tpl.ParseGlob(filename)
+		_, err = tpl.ParseFS(frontend.Files, filename)
 		if err != nil {
 			return nil, errors.WithMessage(err, "could not parse template")
 		}
@@ -66,7 +67,7 @@ return tpl, nil }
 
 func loadTemplates() (TemplateCollection, error) {
-	templateDir := path.Join("frontend", "templates")
+	templateDir := "templates"
 	templates := make(TemplateCollection, 0)
 
 	layoutFile := path.Join(templateDir, "index.gotmpl")
@@ -78,7 +79,7 @@ } 	templates["index"] = index
 
 	glob := path.Join(templateDir, "blocks", "*.gotmpl")
-	templatePaths, err := filepath.Glob(glob)
+	templatePaths, err := fs.Glob(frontend.Files, glob)
 	if err != nil {
 		return nil, errors.WithMessage(err, "could not glob block templates")
 	}