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
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
|
@ -28,16 +27,7 @@ func servePost(w http.ResponseWriter, r *http.Request) {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// We need to use a buffer here to enable minification
|
render(w, templatePostName, post)
|
||||||
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())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func getPost(context context.Context, path string) (*Post, error) {
|
func getPost(context context.Context, path string) (*Post, error) {
|
||||||
|
|
15
render.go
15
render.go
|
@ -1,8 +1,10 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"html/template"
|
"html/template"
|
||||||
"log"
|
"log"
|
||||||
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
const templatePostName = "post.gohtml"
|
const templatePostName = "post.gohtml"
|
||||||
|
@ -35,3 +37,16 @@ func initRendering() {
|
||||||
log.Fatal(err)
|
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