diff --git a/forms.go b/forms.go index d9949fb..2ceb8ef 100644 --- a/forms.go +++ b/forms.go @@ -23,6 +23,19 @@ var ( ErrParseFailure = errors.New("could not parse value") ) +// Parse uses the given Schema to parse the HTTP form values in the given HTTP +// Request. If the values of the form do not match the schema, or required values +// are missing, a panic is triggered. +func MustParse(r *http.Request, schema Schema) { + if err := r.ParseForm(); err != nil { + panic("forms: " + err.Error()) + } + + if err := ParseValues(r.Form, schema); err != nil { + panic("forms: " + err.Error()) + } +} + // Parse uses the given Schema to parse the HTTP form values in the given HTTP // Request. If the values of the form do not match the schema, or required values // are missing, an error is returned. diff --git a/forms_test.go b/forms_test.go index 8f900f6..67ec10c 100644 --- a/forms_test.go +++ b/forms_test.go @@ -13,6 +13,69 @@ import ( "github.com/shoenig/test/must" ) +func Test_MustParse(t *testing.T) { + t.Parallel() + + request, err := http.NewRequestWithContext( + t.Context(), http.MethodPost, "/", nil, + ) + must.NoError(t, err) + + request.PostForm = make(url.Values) + request.PostForm.Set("one", "1") + request.PostForm.Set("two", "2") + request.PostForm.Set("three", "3.1") + request.PostForm.Set("four", "true") + + var ( + one string + two int + three float64 + four bool + ) + + MustParse(request, Schema{ + "one": String(&one), + "two": Int(&two), + "three": Float(&three), + "four": Bool(&four), + }) + must.Eq(t, "1", one) + must.Eq(t, 2, two) + must.Eq(t, 3.1, three) + must.True(t, four) +} + +func Test_MustParse_panic(t *testing.T) { + t.Parallel() + + request, err := http.NewRequestWithContext( + t.Context(), http.MethodPost, "/", nil, + ) + must.NoError(t, err) + + request.PostForm = make(url.Values) + request.PostForm.Set("one", "1") + request.PostForm.Set("three", "3.1") + request.PostForm.Set("four", "true") + + var ( + one string + two int + three float64 + four bool + ) + + must.Panic(t, func() { + MustParse(request, Schema{ + "one": String(&one), + "two": Int(&two), + "three": Float(&three), + "four": Bool(&four), + }) + }) +} + func Test_Parse_singles(t *testing.T) { t.Parallel()