Skip to content

Commit

Permalink
Merge pull request #78 from ggicci/fix/77-default-bug
Browse files Browse the repository at this point in the history
fix: decode with default directive only works the first time
  • Loading branch information
ggicci committed Oct 29, 2023
2 parents a432745 + 7ca7bd9 commit 5317ab1
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 5 deletions.
5 changes: 2 additions & 3 deletions default.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,13 @@ func defaultValueSetter(ctx *DirectiveRuntime) error {

// Transform:
// 1. ctx.Argv -> input values
// 2. ["default"] -> ctx.Argv
// 2. ["default"] -> keys
extractor := &extractor{
Form: multipart.Form{
Value: map[string][]string{
"default": ctx.Directive.Argv,
},
},
}
ctx.Directive.Argv = []string{"default"}
return extractor.Execute(ctx)
return extractor.Execute(ctx, "default")
}
28 changes: 28 additions & 0 deletions default_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,31 @@ func TestDirectiveDefault_PatchField(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, expected, got)
}

// FIX: https://github.com/ggicci/httpin/issues/77
// Decode parameter struct with default values only works the first time
func TestDirectiveDeafult_Decode_twice(t *testing.T) {
type ThingWithDefaultValues struct {
Id uint `in:"query=id;required"`
Page int `in:"query=page;default=1"`
PerPage int `in:"query=page_size;default=127"`
}

r, _ := http.NewRequest("GET", "/?id=123", nil)
expected := &ThingWithDefaultValues{
Id: 123,
Page: 1,
PerPage: 127,
}

// First decode works as expected
xxx := ThingWithDefaultValues{}
err := Decode(r, &xxx)
assert.NoError(t, err)
assert.Equal(t, expected, &xxx)

// Second decode generates eror
err = Decode(r, &xxx)
assert.NoError(t, err)
assert.Equal(t, expected, &xxx)
}
7 changes: 5 additions & 2 deletions extractor.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ func newExtractor(r *http.Request) *extractor {
}
}

func (e *extractor) Execute(ctx *DirectiveRuntime) error {
for _, key := range ctx.Directive.Argv {
func (e *extractor) Execute(ctx *DirectiveRuntime, keys ...string) error {
if len(keys) == 0 {
keys = ctx.Directive.Argv
}
for _, key := range keys {
if e.KeyNormalizer != nil {
key = e.KeyNormalizer(key)
}
Expand Down

0 comments on commit 5317ab1

Please sign in to comment.