From 83ac76795c4e74ac3f259456a63d060617e939a3 Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Sat, 15 Feb 2025 09:58:30 -0500 Subject: [PATCH] Using embedded fs for static --- internal/server/server.go | 8 ++++++-- ui/efs.go | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 ui/efs.go diff --git a/internal/server/server.go b/internal/server/server.go index bb12d30..bb47ca6 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -6,6 +6,7 @@ import ( "net/http" "git.runcible.io/learning/ratchet/internal/model" + "git.runcible.io/learning/ratchet/ui" "github.com/alexedwards/scs/v2" "github.com/go-playground/form/v4" ) @@ -31,11 +32,14 @@ func NewRatchetApp(logger *slog.Logger, tc *TemplateCache, db *sql.DB, sm *scs.S rs.templateCache = tc rs.sessionManager = sm // TODO implement middleware that disables directory listings - fileServer := http.FileServer(http.Dir("./ui/static/")) + // This line was superceded by using the embedded filesystem + // fileServer := http.FileServer(http.Dir("./ui/static/")) router := http.NewServeMux() // Subtree pattern for static assets - router.Handle("GET /static/", http.StripPrefix("/static/", fileServer)) + // This line was superceded by using the embedded filesystem + // router.Handle("GET /static/", http.StripPrefix("/static/", fileServer)) + router.Handle("GET /static/", http.FileServerFS(ui.Files)) // Mux Router implements the Handler interface. AKA it has a ServeHTTP receiver. // SEE we can really clean things up by moving this into routes.go and handlers.go diff --git a/ui/efs.go b/ui/efs.go new file mode 100644 index 0000000..346a707 --- /dev/null +++ b/ui/efs.go @@ -0,0 +1,14 @@ +package ui + +import "embed" + +// The below is actually a comment directive. Comment directives must be +// placed immediately above the variable used. The path provided is relative +// to the .go file it is in. You can only embed on global variables at a package +// level. Paths cannot contain . or .. or begin with / So you are effectively +// restricted to embedding files within the same directory as the .go file. +// Lastly the embedded file system is always rooted in the directory that contains +// the embed directive. So in this example the root is in our ui dir. + +//go:embed "static" +var Files embed.FS