hooks: Recursively search embedded fields for methods (#494)
* hooks: Recursively search embedded fields for methods
Follow up to #493 and 840220c
Kong currently supports hooks on embedded fields of a parsed node,
but only at the first level of embedding:
```
type mainCmd struct {
FooOptions
}
type FooOptions struct {
BarOptions
}
func (f *FooOptions) BeforeApply() error {
// this will be called
}
type BarOptions struct {
}
func (b *BarOptions) BeforeApply() error {
// this will not be called
}
```
This change adds support for hooks to be defined
on embedded fields of embedded fields so that the above
example would work as expected.
Per #493, the definition of "embedded" field is adjusted to mean:
- Any anonymous (Go-embedded) field that is exported
- Any non-anonymous field that is tagged with `embed:""`
*Testing*:
Includes a test case for embedding an anonymous field in an `embed:""`
and an `embed:""` field in an anonymous field.
* Use recursion to build up the list of receivers
The 'receivers' parameter helps avoid constant memory allocation
as the backing storage for the slice is reused across recursive calls.
This commit is contained in:
@@ -2405,6 +2405,8 @@ func TestProviderMethods(t *testing.T) {
|
||||
}
|
||||
|
||||
type EmbeddedCallback struct {
|
||||
Nested NestedCallback `embed:""`
|
||||
|
||||
Embedded bool
|
||||
}
|
||||
|
||||
@@ -2414,6 +2416,8 @@ func (e *EmbeddedCallback) AfterApply() error {
|
||||
}
|
||||
|
||||
type taggedEmbeddedCallback struct {
|
||||
NestedCallback
|
||||
|
||||
Tagged bool
|
||||
}
|
||||
|
||||
@@ -2422,6 +2426,15 @@ func (e *taggedEmbeddedCallback) AfterApply() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type NestedCallback struct {
|
||||
nested bool
|
||||
}
|
||||
|
||||
func (n *NestedCallback) AfterApply() error {
|
||||
n.nested = true
|
||||
return nil
|
||||
}
|
||||
|
||||
type EmbeddedRoot struct {
|
||||
EmbeddedCallback
|
||||
Tagged taggedEmbeddedCallback `embed:""`
|
||||
@@ -2441,9 +2454,15 @@ func TestEmbeddedCallbacks(t *testing.T) {
|
||||
expected := &EmbeddedRoot{
|
||||
EmbeddedCallback: EmbeddedCallback{
|
||||
Embedded: true,
|
||||
Nested: NestedCallback{
|
||||
nested: true,
|
||||
},
|
||||
},
|
||||
Tagged: taggedEmbeddedCallback{
|
||||
Tagged: true,
|
||||
NestedCallback: NestedCallback{
|
||||
nested: true,
|
||||
},
|
||||
},
|
||||
Root: true,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user