/
helpers.go
47 lines (39 loc) · 1.26 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
import (
"bytes"
"fmt"
"net/http"
"runtime/debug"
)
func (app *application) serverError(w http.ResponseWriter, err error) {
trace := fmt.Sprintf("%s\n%s", err.Error(), debug.Stack())
app.errorLog.Println(trace)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
func (app *application) clientError(w http.ResponseWriter, status int) {
http.Error(w, http.StatusText(status), status)
}
func (app *application) notFound(w http.ResponseWriter) {
app.clientError(w, http.StatusNotFound)
}
func (app *application) render(w http.ResponseWriter, r *http.Request, name string, td *templateData) {
ts, ok := app.templateCache[name]
if !ok {
app.serverError(w, fmt.Errorf("The template %s does not exist", name))
return
}
// Initialize a new buffer.
buf := new(bytes.Buffer)
// Write the template to the buffer, instead of straight to the
// http.ResponseWriter. If there's an error, call our serverError helper and then
// return.
err := ts.Execute(buf, td)
if err != nil {
app.serverError(w, err)
return
}
// Write the contents of the buffer to the http.ResponseWriter. Again, this
// is another time where we pass our http.ResponseWriter to a function that
// takes an io.Writer.
buf.WriteTo(w)
}