Move buffering and execution of templates to own func

This commit is contained in:
Jan-Lukas Else 2020-07-31 19:46:12 +02:00
parent c3449faec6
commit 0175ce1729
2 changed files with 16 additions and 11 deletions

View File

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

View File

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