Skip to content

Commit

Permalink
Fix optional
Browse files Browse the repository at this point in the history
  • Loading branch information
Maxim Bovtunov committed Dec 24, 2020
1 parent c7cdc05 commit 8e828e0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ The format is based on
project adheres to
[Semantic Versioning](https://semver.org/spec/v2.0.0.html): TBD, use modules or another vendor system.

## v1.6.3

### Fixed

- Fix `optional` fields resolving.

## v1.6.2

### Fixed
Expand Down
19 changes: 19 additions & 0 deletions container_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -976,6 +976,25 @@ func TestContainer_Inject(t *testing.T) {
require.Nil(t, extracted.server)
})

t.Run("resolve group in params", func(t *testing.T) {
c, err := di.New()
require.NoError(t, err)

type Fn func()
type Params struct {
di.Inject
Handlers []Fn `optional:"true"`
}
require.NoError(t, c.Provide(func() Fn { return func() {} }))
require.NoError(t, c.Provide(func() Fn { return func() {} }))
require.NoError(t, c.Provide(func(params Params) bool {
return len(params.Handlers) == 2
}))
var extracted bool
require.NoError(t, c.Resolve(&extracted))
require.True(t, extracted)
})

t.Run("optional group may be nil", func(t *testing.T) {
c, err := di.New()
require.NoError(t, err)
Expand Down
9 changes: 8 additions & 1 deletion inject.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ type field struct {
func parseField(f reflect.StructField) (field, bool) {
tags := Tags{}
t := string(f.Tag)
optional := false
// this code copied from reflect.StructField.Lookup() method.
for t != "" {
// Skip leading space.
Expand Down Expand Up @@ -91,12 +92,18 @@ func parseField(f reflect.StructField) (field, bool) {
if name == "skip" && value == "true" {
return field{}, false
}
if name == "optional" {
if value == "true" {
optional = true
}
continue
}
tags[name] = value
}
return field{
rt: f.Type,
tags: tags,
optional: tags["optional"] == "true",
optional: optional,
}, true
}

Expand Down

0 comments on commit 8e828e0

Please sign in to comment.