iris
iris copied to clipboard
[BUG/FUTURE] add custom IsDestType in RegisterDependency
hasPanic := false
app.ConfigureContainer(func(container *router.APIContainer) {
container.EnableStrictMode(true)
defer func() {
if e := recover(); e != nil {
hasPanic = true
}
}()
type good_willInitPanic struct {
}
container.Handle(http.MethodGet, "/struct1", func(good_willInitPanic) string {
return "1"
})
})
require.True(t, hasPanic)
called := 0
hasPanic = false
app.ConfigureContainer(func(container *router.APIContainer) {
type bad_IWillInitPanic struct {
}
container.EnableStrictMode(true)
container.RegisterDependency(&hero.Dependency{
Handle: func(ctx *context.Context, input *hero.Input) (reflect.Value, error) {
called++
return reflect.Value{}, hero.ErrSeeOther
},
DestType: nil,
/*
// todo: your can add field IsDestType
IsDestType : func(input *hero.Input) bool{
return input.Type == reflect.TypeOf(bad_IWillInitPanic{})
|| or other logic: example isEmbedsType(input.Type, xxx)
|| or index check
|| or replace hero matchDependency()
},
*/
})
defer func() {
if e := recover(); e != nil {
hasPanic = true
}
}()
container.Handle(http.MethodGet, "/struct2", func(bad_IWillInitPanic) string {
return "2"
})
})
require.True(t, hasPanic) // not support
go (func() {
time.Sleep(time.Second * 1)
//http.Get("http://127.0.0.1:8080/struct1")
http.Get("http://127.0.0.1:8080/struct2") // bad function: only find error when request it.
})()
if err := app.Listen(":8080"); err != nil {
fmt.Println(err)
}
Hello @RelicOfTesla,
I've pushed a commit which does that and more. Now you have the option to change the default way of how "matchDependency" behaves with two ways:
- In API DI Container, so all dependencies share the same "matchDependency" using the
container.SetDependencyMatcher(func(d *hero.Dependnecy, in reflect.Type) bool{...})
- At Dependency-level itself by
&hero.Dependency { Match: func(in reflect.Type) bool {...}, ...}
Take a look and share your feedbad, don't hesitate to ask more!
Thanks. In addition, it is recommended to use “hero.input” as the parameter of match, so that the Parameter sequence index bind may be controlled in the future. Or it can carry “Route“ and more in “hero.input“ for more complex context control in the future. Although I don't need such advanced functions for the time being. :)
[bug] old source code panic when RegisterDependency(&hero.Dependency{ /Match : nil/, ...... })
Hello @RelicOfTesla, why do you manually construct a &hero.Dependency? I can't control the parameters there. You should just use RegisterDependency(customStructValueOrFunctionHere).