Enhancement: `form.Marshaler` and `form.Unmarshaler`
Fixes Or Enhances
Add support for custom marshalling and unmarshalling to a struct.
The motivation behind this mainly comes from using generics, when looking to register a custom encoder/decoder, you have to register one for every generic implementation of a struct, so for example:
type MyGenericStruct[T any] struct {
T T
}
decoder := form.NewDecoder()
decoder.RegisterCustomTypeFunc(func(x any) ([]string, error) {
return // values
}, MyGenericStruct[Type1]{})
decoder.RegisterCustomTypeFunc(func(x any) ([]string, error) {
return // values
}, MyGenericStruct[Type2]{})
// etc...
This isn't really great, so instead with these marshaller interfaces we can simply do:
func (g *MyGenericStruct[T]) UnmarshalForm(ss []string) error {
// Custom handling
return nil
}
func (g MyGenericStruct[T]) MarshalForm() ([]string, error) {
s := []string{}
// build s
return s, nil
}
Make sure that you've checked the boxes below before you submit PR:
- [x] Tests exist or have been written that cover this particular change.
@go-playground/admins
coverage: 99.646% (-0.2%) from 99.814% when pulling b0456709f41acee07522c41a3b245d5fc70719df on tigh-latte:enhancement/custom-marshaller into 8785d3ce031b7f042da48a63a4ea5b03cae12f6f on go-playground:master.
Looks like gofumpt also made a number of formatting edits. Let me know if this is something yous don't want.
Thank you for the PR @tigh-latte! I think this would be an amazing addition and will take a deeper look at it this weekend.
I already took a cursory look and code looks solid, I am only thinking about the interface and its signature function/method name.
Sure thing, let me know if you have any better/preferred suggestions.