From bcb9d77de04ee2a8a8bc23262dfb9b15b8efe0d5 Mon Sep 17 00:00:00 2001 From: Nikita Tokarchuk Date: Fri, 3 Dec 2021 02:50:31 +0100 Subject: [PATCH] Implement template writer helper --- frontend/renderer/output.go | 38 +++++++++++++++++++++++++++++++++++++ go.mod | 1 + 2 files changed, 39 insertions(+) create mode 100644 frontend/renderer/output.go diff --git a/frontend/renderer/output.go b/frontend/renderer/output.go new file mode 100644 index 0000000..d9caa33 --- /dev/null +++ b/frontend/renderer/output.go @@ -0,0 +1,38 @@ +package renderer + +import ( + "io" + + "code.tokarch.uk/mainnika/nikita-tokarch-uk/frontend/templates" + routing "github.com/jackwhelpton/fasthttp-routing/v2" + "github.com/valyala/fasthttp" +) + +var _ routing.DataWriter = (*TemplateWriter)(nil) + +// staticWriter is thread-safe static instance of template writer +var staticWriter = &TemplateWriter{} + +// TemplateWriter is the fasthttp data writer that loads and executes template using the content +type TemplateWriter struct{} + +// SetHeader sets the content type to HTML since all templates are HTML +func (tw *TemplateWriter) SetHeader(rh *fasthttp.ResponseHeader) { + rh.SetContentType(routing.MIME_HTML) +} + +// Write executes the template and writes result to the response writer +func (tw *TemplateWriter) Write(w io.Writer, content interface{}) error { + + template := templates.GetTemplateOf(content) + + return template.Execute(w, content) +} + +// useTemplateWriter is the routing middleware to set the default data writer +func (r *Renderer) useTemplateWriter(c *routing.Context) (err error) { + + c.SetDataWriter(staticWriter) + + return +} diff --git a/go.mod b/go.mod index 84f71cf..aacb4ed 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module code.tokarch.uk/mainnika/nikita-tokarch-uk go 1.17 require ( + github.com/jackwhelpton/fasthttp-routing/v2 v2.0.0 github.com/sirupsen/logrus v1.8.1 github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.9.0