From 0175ce1729a9cef716c5c3de6ca69bd2fdc7ad10 Mon Sep 17 00:00:00 2001 From: Jan-Lukas Else Date: Fri, 31 Jul 2020 19:46:12 +0200 Subject: [PATCH] Move buffering and execution of templates to own func --- posts.go | 12 +----------- render.go | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/posts.go b/posts.go index b3b4738..ce72267 100644 --- a/posts.go +++ b/posts.go @@ -1,7 +1,6 @@ package main import ( - "bytes" "context" "database/sql" "errors" @@ -28,16 +27,7 @@ func servePost(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - // We need to use a buffer here to enable minification - var buffer bytes.Buffer - err = templates.ExecuteTemplate(&buffer, templatePostName, post) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - // Set content type (needed for minification middleware - w.Header().Set("Content-Type", contentTypeHTML) - // Write buffered response - _, _ = w.Write(buffer.Bytes()) + render(w, templatePostName, post) } func getPost(context context.Context, path string) (*Post, error) { diff --git a/render.go b/render.go index 50f63da..c723953 100644 --- a/render.go +++ b/render.go @@ -1,8 +1,10 @@ package main import ( + "bytes" "html/template" "log" + "net/http" ) const templatePostName = "post.gohtml" @@ -35,3 +37,16 @@ func initRendering() { log.Fatal(err) } } + +func render(w http.ResponseWriter, template string, data interface{}) { + // We need to use a buffer here to enable minification + var buffer bytes.Buffer + err := templates.ExecuteTemplate(&buffer, template, data) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + // Set content type (needed for minification middleware + w.Header().Set("Content-Type", contentTypeHTML) + // Write buffered response + _, _ = w.Write(buffer.Bytes()) +}