learn-go/snippetbox/cmd/web/helpers.go

95 lines
2.1 KiB
Go
Raw Normal View History

package main
import (
2024-01-25 23:06:28 +00:00
"bytes"
2024-02-07 00:46:46 +00:00
"errors"
2024-01-25 23:06:28 +00:00
"fmt"
"log/slog"
"net/http"
"runtime/debug"
2024-01-25 23:43:07 +00:00
"time"
2024-02-07 00:46:46 +00:00
"github.com/go-playground/form/v4"
2024-02-08 07:04:06 +00:00
"github.com/justinas/nosurf"
)
2024-01-25 23:43:07 +00:00
// newTemplateData ...
2024-02-08 06:46:35 +00:00
func (app *application) newTemplateData(r *http.Request) templateData {
2024-01-25 23:43:07 +00:00
return templateData{
2024-02-08 06:46:35 +00:00
CurrentYear: time.Now().Year(),
Flash: app.sessionManager.PopString(r.Context(), "flash"),
IsAuthenticated: app.isAuthenticated(r),
2024-02-08 07:04:06 +00:00
CSRFToken: nosurf.Token(r),
2024-01-25 23:43:07 +00:00
}
}
2024-01-25 23:06:28 +00:00
// 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)
}
2024-02-07 00:46:46 +00:00
// (app *application) ...
func (app *application) decodePostForm(r *http.Request, dst any) error {
err := r.ParseForm()
if err != nil {
return err
}
err = app.formDecoder.Decode(dst, r.PostForm)
if err != nil {
var invalidDecoderError *form.InvalidDecoderError
if errors.As(err, &invalidDecoderError) {
panic(err)
}
return err
}
return nil
}
2024-02-08 06:46:35 +00:00
func (app *application) isAuthenticated(r *http.Request) bool {
2024-02-08 17:26:25 +00:00
isAuthenticated, ok := r.Context().Value(isAuthenticatedContextKey).(bool)
if !ok {
return false
}
return isAuthenticated
2024-02-08 06:46:35 +00:00
}