form icon indicating copy to clipboard operation
form copied to clipboard

Enhancement: `form.Marshaler` and `form.Unmarshaler`

Open tigh-latte opened this issue 1 year ago • 4 comments

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

tigh-latte avatar May 09 '24 11:05 tigh-latte

Coverage Status

coverage: 99.646% (-0.2%) from 99.814% when pulling b0456709f41acee07522c41a3b245d5fc70719df on tigh-latte:enhancement/custom-marshaller into 8785d3ce031b7f042da48a63a4ea5b03cae12f6f on go-playground:master.

coveralls avatar May 09 '24 11:05 coveralls

Looks like gofumpt also made a number of formatting edits. Let me know if this is something yous don't want.

tigh-latte avatar May 09 '24 11:05 tigh-latte

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.

deankarn avatar May 11 '24 15:05 deankarn

Sure thing, let me know if you have any better/preferred suggestions.

tigh-latte avatar May 11 '24 16:05 tigh-latte