Skip to content

Commit

Permalink
Add FieldPresent type
Browse files Browse the repository at this point in the history
  • Loading branch information
TomWright committed Nov 27, 2019
1 parent 1176508 commit 62175d1
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
9 changes: 9 additions & 0 deletions parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ var (
ErrInvalidTag = errors.New("invalid tag")
)

type FieldPresent bool

var parameterPresentType = reflect.TypeOf(FieldPresent(false))

// DefaultParser is a default parser.
var DefaultParser = &Parser{
Tag: "queryparam",
Expand Down Expand Up @@ -89,6 +93,11 @@ func (p *Parser) ParseField(field reflect.StructField, value reflect.Value, urlV
return nil
}

if field.Type == parameterPresentType {
value.SetBool(true)
return nil
}

valueParser, ok := p.ValueParsers[field.Type]
if !ok {
return fmt.Errorf("%w: %s: %v", ErrUnhandledFieldType, field.Name, field.Type.String())
Expand Down
37 changes: 37 additions & 0 deletions parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,43 @@ func TestParser_Parse(t *testing.T) {
t.Errorf("unexpected error: %v", err)
}
})

t.Run("FieldPresent", func(t *testing.T) {
t.Parallel()

p := &queryparam.Parser{
Tag: "queryparam",
DelimiterTag: "queryparamdelim",
Delimiter: ",",
ValueParsers: map[reflect.Type]queryparam.ValueParser{},
}

urlValues := url.Values{}
urlValues.Set("first-name", "Tom")
urlValues.Set("last-name", "")
urlValues.Set("age", "26")

type testData struct {
FirstName queryparam.FieldPresent `queryparam:"first-name"`
LastName queryparam.FieldPresent `queryparam:"last-name"`
Age queryparam.FieldPresent `queryparam:"age"`
}
var res testData

if err := p.Parse(urlValues, &res); err != nil {
t.Errorf("unexpected error: %v", err)
return
}

exp := testData{
FirstName: true,
LastName: false,
Age: true,
}
if !reflect.DeepEqual(exp, res) {
t.Errorf("expected result:\n%v\ngot result:\n%v\n", exp, res)
}
})
}

func TestParse_FieldWithNoTagIsNotUsed(t *testing.T) {
Expand Down

0 comments on commit 62175d1

Please sign in to comment.