From 5b2eab10f015382fc6e919fd5a8f948693a09292 Mon Sep 17 00:00:00 2001 From: Nikita Tokarchuk Date: Fri, 3 Dec 2021 02:26:03 +0100 Subject: [PATCH] Parse compiled-in go templates on app start --- frontend/main.go | 2 ++ frontend/templates/templates.go | 51 +++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 frontend/templates/templates.go diff --git a/frontend/main.go b/frontend/main.go index 757f509..9346ef8 100644 --- a/frontend/main.go +++ b/frontend/main.go @@ -9,6 +9,8 @@ import ( "github.com/valyala/fasthttp" "code.tokarch.uk/mainnika/nikita-tokarch-uk/frontend/config" + + _ "code.tokarch.uk/mainnika/nikita-tokarch-uk/frontend/templates" ) var Version = "nightly" diff --git a/frontend/templates/templates.go b/frontend/templates/templates.go new file mode 100644 index 0000000..84cdb8d --- /dev/null +++ b/frontend/templates/templates.go @@ -0,0 +1,51 @@ +package templates + +import ( + "bytes" + "embed" + "html/template" + "io/fs" + + "github.com/sirupsen/logrus" +) + +// Static go-templates source +var content embed.FS + +// List of compiled go-templates +var Templates *template.Template + +// Load embeded templates +func init() { + + Templates = template.New("") + + tmplNames, err := fs.Glob(content, "*.go.tmpl") + if err != nil { + panic(err) + } + + buf := bytes.NewBuffer(nil) + + for _, name := range tmplNames { + + buf.Reset() + + tmplContent, err := content.Open(name) + if err != nil { + panic(err) + } + size, err := buf.ReadFrom(tmplContent) + if err != nil { + panic(err) + } + tmpl, err := Templates.New(name).Parse(buf.String()) + if err != nil { + panic(err) + } + + logrus.Debugf("Found template: %s, size:%d", tmpl.Name(), size) + } + + logrus.Debugf("Templates loading complete%s", Templates.DefinedTemplates()) +}