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.
This commit is contained in:
Victor Vrantchan
2021-02-20 19:02:45 -05:00
parent 695856b205
commit ec514fd70e
4 changed files with 24 additions and 5 deletions

View File

@@ -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 {

View File

@@ -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 {

19
pkg/frontend/context.go Normal file
View File

@@ -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
}

View File

@@ -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),