mirror of https://github.com/jlelse/GoBlog
Move buffering and execution of templates to own func
This commit is contained in:
parent
c3449faec6
commit
0175ce1729
12
posts.go
12
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) {
|
||||
|
|
15
render.go
15
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())
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue