From ec514fd70e31cd2a6d21c532b28a3139552ee94f Mon Sep 17 00:00:00 2001 From: Victor Vrantchan Date: Sat, 20 Feb 2021 19:02:45 -0500 Subject: [PATCH] add form data to context When calling frontend.Fail pass the form data in the context. In case of an error, returns the values back so they're not reset on the page. --- internal/frontend/account/login.go | 4 ++-- internal/frontend/account/register.go | 4 ++-- pkg/frontend/context.go | 19 +++++++++++++++++++ pkg/frontend/frontend.go | 2 +- 4 files changed, 24 insertions(+), 5 deletions(-) create mode 100644 pkg/frontend/context.go diff --git a/internal/frontend/account/login.go b/internal/frontend/account/login.go index 7c375b05..4b4df28c 100644 --- a/internal/frontend/account/login.go +++ b/internal/frontend/account/login.go @@ -14,8 +14,6 @@ import ( func (srv server) loginForm(w http.ResponseWriter, r *http.Request) { var ( - ctx = r.Context() - logger = log.FromContext(ctx) email = r.FormValue("email") password = r.FormValue("password") data = frontend.Data{ @@ -25,6 +23,8 @@ func (srv server) loginForm(w http.ResponseWriter, r *http.Request) { "password": password, }, } + ctx = frontend.AddFormData(r.Context(), data) + logger = log.FromContext(ctx) ) if r.Method == http.MethodGet { diff --git a/internal/frontend/account/register.go b/internal/frontend/account/register.go index 7f29ceae..73642ea9 100644 --- a/internal/frontend/account/register.go +++ b/internal/frontend/account/register.go @@ -13,8 +13,6 @@ import ( func (srv server) registerForm(w http.ResponseWriter, r *http.Request) { var ( - ctx = r.Context() - logger = log.FromContext(ctx) username = r.FormValue("username") email = r.FormValue("email") password = r.FormValue("password") @@ -26,6 +24,8 @@ func (srv server) registerForm(w http.ResponseWriter, r *http.Request) { "password": password, }, } + ctx = frontend.AddFormData(r.Context(), data) + logger = log.FromContext(ctx) ) if r.Method == http.MethodGet { diff --git a/pkg/frontend/context.go b/pkg/frontend/context.go new file mode 100644 index 00000000..0d8ca09b --- /dev/null +++ b/pkg/frontend/context.go @@ -0,0 +1,19 @@ +package frontend + +import "context" + +type key int + +const dataKey key = 0 + +func AddFormData(ctx context.Context, data Data) context.Context { + return context.WithValue(ctx, dataKey, data) +} + +func dataFromContext(ctx context.Context) Data { + v, ok := ctx.Value(dataKey).(Data) + if !ok { + return Data{} + } + return v +} diff --git a/pkg/frontend/frontend.go b/pkg/frontend/frontend.go index fe192d89..b495208f 100644 --- a/pkg/frontend/frontend.go +++ b/pkg/frontend/frontend.go @@ -174,7 +174,7 @@ func (srv *Server) Fail(ctx context.Context, w http.ResponseWriter, err error, k } if errors.As(err, &validationErr) { - srv.RenderTemplate(ctx, w, tpl, Data{}. + srv.RenderTemplate(ctx, w, tpl, dataFromContext(ctx). FormErrors(validationErr.Invalid()). WithLog(err, keyvals...). WithCode(http.StatusBadRequest),