3 ms·
>couldn't think of a way that did not end up using reflection The builtin decoders (eg, json) use reflection. You don't lose any of the benefits of static typi
by aaronblohowiak 12y ago
>couldn't think of a way that did not end up using reflection
The builtin decoders (eg, json) use reflection. You don't lose any of the benefits of static typing as you are still decoding into your statically-typed object.
I would separate form parsing from object validation.
Use something like this: https://github.com/ajg/form https://github.com/ajg/form to populate statically-typed go structs from form data, and then validate your objects.
- aaron-lebo 12y agoThere is a speed hit to reflection, though, right? Also, you do lose the benefit of static typing, for example, the following typo isn't picked up at compile time: type User struct { Name string `form:"nam"` } Tags are rather ugly and don't scale to many options well. What happens when your ORM, form validation library, xml library, and json libraries each need a separate tag? That's a slight exaggeration but you could see how the apparent simplicity in the form example can quickly become anything but. Heavy use of tags (and reflection) just makes me feel like you have to work around the language too much and I question whether you may as well just use Python, hence my original question. I've done minimal work with Go, though, so perhaps I'm misinformed.
- placeybordeaux 12y agoThere is a speed hit to reflection. As for the tag issue: writing your own marshaler isn't actually a huge problem. I have been meaning to write my own json marshaler for a while. I personally find the solution much more paletable than many other ways of marshaling in and out of json.
- dsymonds 12y agoThere's a significant speed hit to reflection, but it's going to get lost in the noise if you're making HTTP requests.
- cakoose 12y agoYou're example is not a static typing issue. It's a feature of the library that the struct field doesn't have to have the same name as the form field. I think the issue is more of a DRY thing, which could maybe be fixed with something like: type User struct { FirstName string `form:lowercase_hyphenated` LastName string `form:lowercase_hyphenated` } This hypothetical syntax would instruct the library to look for the form fields "first-name" and "last-name".