Add InterfaceCustomUnmarshaler
ozraru opened this issue · comments
Is your feature request related to a problem? Please describe.
I want to make an unmarshaler of the interface.
The interface includes several structs. And it can be identified with type
field.
I've tried to make CustomUnmarshaler, but there is no CustomUnmarshaler which have the same function as InterfaceUnmarshaler.
Describe the solution you'd like
Add
func CustomInterfaceUnmarshaler[T any](unmarshaler func(*T, func(interface{}) error) error) DecodeOption
func RegisterCustomInterfaceUnmarshaler[T any](unmarshaler func(*T, func(interface{}) error) error)
Describe alternatives you've considered
I've tried to implement InterfaceUnmarshaler, but the interface cannot have function.
Additional context
Example to use
type MyInterface interface {
foo()
}
type MyStruct1 struct {
UniqueField1 string
}
func (m *MyStruct1) foo() {}
type MyStruct2 struct {
UniqueField2 string
}
func (m *MyStruct2) foo() {}
type MyStruct3 struct {
UniqueField3 string
}
func (m *MyStruct3) foo() {}
func init() {
yaml.RegisterCustomInterfaceUnmarshaler[MyInterface](func(s *MyInterface, unmarshal func(interface{}) error) error {
var typeSchema struct {
Type string `json:"type"`
}
if err := unmarshal(&typeSchema); err != nil {
return err
}
switch typeSchema.Type {
case "str1":
str1 := MyStruct1{}
if err := unmarshal(&str1); err != nil {
return err
}
*s = &str1
return nil
case "str2":
str2 := MyStruct1{}
if err := unmarshal(&str2); err != nil {
return err
}
*s = &str2
return nil
case "str3":
str3 := MyStruct1{}
if err := unmarshal(&str3); err != nil {
return err
}
*s = &str3
return nil
default:
return ErrInvalidType
}
})
}