Embed template files in server binary

This commit is contained in:
Lucas Schumacher 2024-08-01 00:42:35 -04:00
parent 5adfeefa33
commit 1d6e8a9811
3 changed files with 22 additions and 6 deletions

12
main.go
View File

@ -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)

6
templates/fs.go Normal file
View File

@ -0,0 +1,6 @@
package templates
import "embed"
//go:embed *
var FS embed.FS

View File

@ -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 {