mirror of
https://github.com/micromdm/micromdm/
synced 2026-08-07 18:15:47 +08:00
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:
@@ -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 {
|
||||
|
||||
@@ -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
19
pkg/frontend/context.go
Normal 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
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
Reference in New Issue
Block a user