Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions forms.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,26 @@ func (p *stringsParser[T]) Parse(values []string) error {
}

// Strings is used to extract a form data value into a slice of Go strings.
//
// If the form value is missing, then an error is returned during parsing.
func Strings[T StringType](s *[]T) Parser {
return &stringsParser[T]{
required: true,
destination: s,
}
}

// StringsOr is used to extract multiple form values for a given key into a slice of Go strings.
//
// If the form value is missing, then the given alt value is used instead.
func StringsOr[T StringType](s *[]T, alt []T) Parser {
*s = alt
return &stringsParser[T]{
required: false,
destination: s,
}
}

// Secret is used to extract a form data value into a Go conceal.Text. If the
// value is missing then an error is returned during parsing.
func Secret(s **conceal.Text) Parser {
Expand Down
49 changes: 48 additions & 1 deletion forms_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ func Test_Parse_IntType_IntOr(t *testing.T) {
must.Eq(t, 100, age)
}

func Test_Parse_StringType_Strings(t *testing.T) {
func Test_Parse_StringType_Strings_present(t *testing.T) {
t.Parallel()

data := url.Values{
Expand All @@ -379,3 +379,50 @@ func Test_Parse_StringType_Strings(t *testing.T) {
must.NoError(t, err)
must.Eq(t, []string{"alice", "bob", "carol"}, names)
}

func Test_Parse_StringType_Strings_missing(t *testing.T) {
t.Parallel()

data := url.Values{
"names": []string{"alice", "bob", "carol"},
}

var jobs []string

err := ParseValues(data, Schema{
"jobs": Strings(&jobs),
})
must.Error(t, err)
}

func Test_Parse_StringType_StringsOr_present(t *testing.T) {
t.Parallel()

data := url.Values{
"names": []string{"alice", "bob", "carol"},
}

var names []string

err := ParseValues(data, Schema{
"names": StringsOr(&names, []string{"zed", "yulia"}),
})
must.NoError(t, err)
must.Eq(t, []string{"alice", "bob", "carol"}, names)
}

func Test_Parse_StringType_StringsOr_missing(t *testing.T) {
t.Parallel()

data := url.Values{
"names": []string{"alice", "bob", "carol"},
}

var jobs []string

err := ParseValues(data, Schema{
"jobs": StringsOr(&jobs, []string{"janitor", "cashier"}),
})
must.NoError(t, err)
must.Eq(t, []string{"janitor", "cashier"}, jobs)
}
Loading