jsonschema2go
jsonschema2go copied to clipboard
Create a validate function for the generated struct
So when some JSON schema is turned into a struct, wouldn't be cool if a Validate()
method was generated from that struct... Such that we could validate against the JSON schema after unmarshalling JSON into the struct using it's json structtag annotations.
Anyways, just a thought that might be cool, let's do it if we really need it :)
@jonasfj It is on my list of gold-plating nice-to-haves! I'd been considering the same. Regarding the use of struct tags to decorate the types with validation meta data, this unfortunately only applies to structs (which uniquely map to json objects). For example the following types can't in their current form be validated using struct tags:
We also have some non-struct json.RawMessage
types for arbitrary json objects:
- auth.HawkSignatureAuthenticationResponse
- awsprovisioner.GetAllLaunchSpecsResponse
- queue.PostArtifactRequest
- queue.PostArtifactResponse
I'm not sure why in the go language it was decided to only allow tagging of structs rather than arbitrary go types - maybe an oversight, since it covers most use cases but not all... Or maybe intentional.
In any case I think we can still implement, but the validation metadata just won't be attached to go types natively as struct tags, inspectable via reflection - rather there will be a Validate function per type which implicitly knows the bounds that apply to all of its members, and the validation function will be specific per type (implemented as an interface) rather than having a generic validate method that can inspect struct tags via reflection.
The alternative would be to bury all types inside structs - but even this is tricky with arrays which have additional metadata pertaining to the underlying type, and also to the array. :(
The good news is that even though it might be a bit ugly and heavy on generated code - in the end it is still generated code, so as long as it is correct, it doesn't matter too much if there is a lot of it.