ggicci / httpin

🍡 HTTP Input for Go - HTTP Request from/to Go Struct (Bi-directional Data Binding between Go Struct and http.Request)
https://ggicci.github.io/httpin/
MIT License
316 stars 23 forks source link

Can I use pointer types as query params? #63

Closed vamshiaruru32 closed 1 year ago

vamshiaruru32 commented 1 year ago

For example something like

type SearchCollectionParams struct {
    CacheTtl                *int    `in:"query=cacheTtl"`
    DropTokensThreshold     *int    `in:"query=dropTokensThreshold"`
}

Currently I get the error unsupported type *int. The idea is for them to become nil when not provided.

Any help is appreciated, thanks!

vamshiaruru32 commented 1 year ago

I think this might work?

func decodeIntPointer(value string) (interface{}, error) {
    converted, err := strconv.ParseInt(value, 10, 64)
    if err != nil {
        return nil, fmt.Errorf("parse int: %w", err)
    }
    convertedInt := int(converted)
    return &convertedInt, nil
}

func init() {
    val := int(5) // some value
    httpin.RegisterTypeDecoder(reflect.TypeOf(&val), httpin.ValueTypeDecoderFunc(decodeIntPointer))
    httpin.UseGochiURLParam("path", chi.URLParam)
    Validator = validator.New()
}
ggicci commented 1 year ago

Hi @vamshiaruru32 , sorry for the late response, yes the above code can work as expected.

Maybe you also will be interested in the patch field feature released with v0.12.0. Please let me know if you have any concerns to use a patch.Field[int] instead of a *int, thanks in advance :)

vamshiaruru32 commented 1 year ago

Hi @ggicci thanks for the patch pointer. I am partial to using pointers instead of patch.Field container, so I don't think I am going to change those fields right now. But if I do use it in future and find any flaws, I'll reach out again. Since you've confirmed that the code is fine, I'll close the issue. But I'd recommend making this a little bit more obvious in the documentation, I couldn't find much about it and had to go through the code base to figure out :)

ggicci commented 1 year ago

The pointer types are supported automatically now, see v0.14.0.

Playground for examing support of pointer types: https://go.dev/play/p/Aqa9EECplGT