From 277686086ea2eccd00fd66727d8a42e6132ebe6c Mon Sep 17 00:00:00 2001 From: Nikita Tokarchuk Date: Tue, 4 Jan 2022 22:29:53 +0100 Subject: [PATCH] Use constructor-like function to load templates --- cmd/renderer/main.go | 7 ++++++- pkg/templates/templates.go | 12 +++++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/cmd/renderer/main.go b/cmd/renderer/main.go index 43e93e7..854d923 100644 --- a/cmd/renderer/main.go +++ b/cmd/renderer/main.go @@ -12,7 +12,7 @@ import ( "code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/config" "code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/ghost/v4api/httpclient" "code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/routes" - _ "code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/templates" + "code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/templates" ) var Version = "nightly" @@ -52,6 +52,11 @@ func main() { logrus.Fatal(err) } + err = templates.Load() + if err != nil { + logrus.Fatal(err) + } + ghostClient := &httpclient.HTTPClient{ Addr: config.Content.Backend.Addr, Secured: config.Content.Backend.Secured, diff --git a/pkg/templates/templates.go b/pkg/templates/templates.go index 9713638..eb12030 100644 --- a/pkg/templates/templates.go +++ b/pkg/templates/templates.go @@ -24,14 +24,14 @@ var content embed.FS var Templates *template.Template // Load embeded templates -func init() { +func Load() (err error) { Templates = template.New("") Templates.Funcs(UseFuncs()) tmplNames, err := fs.Glob(content, "*.go.tmpl") if err != nil { - panic(err) + return fmt.Errorf("cannot match templates names using glob, %w", err) } buf := bytes.NewBuffer(nil) @@ -42,21 +42,23 @@ func init() { tmplContent, err := content.Open(name) if err != nil { - panic(err) + return fmt.Errorf("cannot open template content, name:%s, %w", name, err) } size, err := buf.ReadFrom(tmplContent) if err != nil { - panic(err) + return fmt.Errorf("cannot read template content, name:%s, %w", name, err) } tmpl, err := Templates.New(name).Parse(buf.String()) if err != nil { - panic(err) + return fmt.Errorf("cannot parse template, name:%s, %w", name, err) } logrus.Debugf("Found template: %s, size:%d", tmpl.Name(), size) } logrus.Debugf("Templates loading complete%s", Templates.DefinedTemplates()) + + return } // MustLookup wraps lookup function for the root template namespace