learn-go/snippetbox/cmd/web/helpers.go
tamsin johnson 3deb2022b8 lets-go:5.4
2024-01-25 15:06:28 -08:00

50 lines
1.1 KiB
Go

package main
import (
"bytes"
"fmt"
"log/slog"
"net/http"
"runtime/debug"
)
// render ...
func (app *application) render(w http.ResponseWriter, r *http.Request, status int, page string, data templateData) {
ts, ok := app.templateCache[page]
if !ok {
err := fmt.Errorf("the template %s does not exist", page)
app.serverError(w, r, err)
return
}
buf := new(bytes.Buffer)
err := ts.ExecuteTemplate(buf, "base", data)
if err != nil {
app.serverError(w, r, err)
return
}
w.WriteHeader(status)
buf.WriteTo(w)
}
func (app *application) serverError(w http.ResponseWriter, r *http.Request, err error) {
var (
method = r.Method
trace = string(debug.Stack())
uri = r.URL.RequestURI()
)
app.logger.Error(err.Error(), slog.String("method", method), slog.String("trace", trace), slog.String("uri", uri))
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)
}