diff --git a/main.go b/main.go index c760a5e..fba1e79 100644 --- a/main.go +++ b/main.go @@ -3,17 +3,17 @@ package main import ( "fmt" "net/http" - "path/filepath" "strings" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" + "git.kealoha.me/lks/lenslocked/templates" "git.kealoha.me/lks/lenslocked/views" ) -func addStaticTemplate(r chi.Router, pattern string, filepath string) { - tpl := views.Must(views.FromFile(filepath)) +func addStaticTemplate(r chi.Router, pattern string, templatePath string) { + tpl := views.Must(views.FromFS(templates.FS, templatePath)) var testWriter strings.Builder err := tpl.ExecuteWriter(&testWriter, nil) @@ -33,9 +33,9 @@ func notFoundHandler(w http.ResponseWriter, r *http.Request) { func main() { r := chi.NewRouter() r.Use(middleware.Logger) - addStaticTemplate(r, "/", filepath.Join("templates", "home.gohtml")) - addStaticTemplate(r, "/contact", filepath.Join("templates", "contact.gohtml")) - addStaticTemplate(r, "/faq", filepath.Join("templates", "faq.gohtml")) + addStaticTemplate(r, "/", "home.gohtml") + addStaticTemplate(r, "/contact", "contact.gohtml") + addStaticTemplate(r, "/faq", "faq.gohtml") r.NotFound(notFoundHandler) fmt.Println("Starting the server on :3000...") http.ListenAndServe(":3000", r) diff --git a/templates/fs.go b/templates/fs.go new file mode 100644 index 0000000..dec2588 --- /dev/null +++ b/templates/fs.go @@ -0,0 +1,6 @@ +package templates + +import "embed" + +//go:embed * +var FS embed.FS diff --git a/views/template.go b/views/template.go index 4688e3d..c29420e 100644 --- a/views/template.go +++ b/views/template.go @@ -4,6 +4,7 @@ import ( "fmt" "html/template" "io" + "io/fs" "log" "net/http" ) @@ -34,6 +35,15 @@ func FromFile(filepath string) (Template, error) { htmlTpl: tpl, }, nil } +func FromFS(fs fs.FS, pattern string) (Template, error) { + tpl, err := template.ParseFS(fs, pattern) + if err != nil { + return Template{}, fmt.Errorf("Error parsing template: %v", err) + } + return Template{ + htmlTpl: tpl, + }, nil +} func Must(t Template, err error) Template { if err != nil {