quicktype icon indicating copy to clipboard operation
quicktype copied to clipboard

[FEATURE]: Go validator tags support

Open timsofteng opened this issue 1 year ago • 1 comments

It would be great if quicktype produce validate tags for go structures.

Input Format: JSONSchema Output Language: go

Description

Unfortunately in go there are no way add validation tags to json without external library. The most popular library currently is validator from google (https://github.com/go-playground/validator). It will give an abillity to validate json data in go applications.

Current Behaviour / Output

This json schema

{
  "id": "http://json-schema.org/geo",
  "$schema": "http://json-schema.org/draft-06/schema#",
  "description": "A geographical coordinate",
  "type": "object",
  "properties": {
    "latitude": {
      "type": "number",
      "minLength": 5
    },
    "ll": {
      "type": "number",
      "minLength": 5
    },
    "longitude": {
      "type": "number"
    }
  }
}

will be generated into this go struct

type Coordinate struct {
	Latitude  *float64 `json:"latitude,omitempty"`
	Ll        *float64 `json:"ll,omitempty"`
	Longitude *float64 `json:"longitude,omitempty"`
}

Proposed Behaviour / Output

This json schema

{
  "id": "http://json-schema.org/geo",
  "$schema": "http://json-schema.org/draft-06/schema#",
  "description": "A geographical coordinate",
  "type": "object",
  "properties": {
    "latitude": {
      "type": "number",
      "minLength": 5
    },
    "ll": {
      "type": "number",
      "minLength": 5
    },
    "longitude": {
      "type": "number"
    }
  }
}

will be generated into this go struct

type Coordinate struct {
	Latitude  *float64 `json:"latitude,omitempty" validate:"min=5"`
	Ll        *float64 `json:"ll,omitempty", validate:"min=5"`
	Longitude *float64 `json:"longitude,omitempty"`
}

Solution

Alternatives

Context

timsofteng avatar Nov 25 '24 19:11 timsofteng

I think instead of tying this directly towards the validator library (which may not be the go-to validation library for everyone/ever), a more general approach can be considered. For instance, inspiration could be taken from the oapi-codegen tool for OpenAPI specifications. They define some OpenAPI extensions that can be used to add any struct field tags in general and control other properties of the generated code.

I am not sure what extensions JSON schema allows, so that may or may not limit this approach. A downside of this approach would also be that one needs to be in control of the schema to add such extensions, which is not always the case. Alternatively one could vendor it, but that is inconvenient.

kristiansvalland avatar Feb 12 '25 12:02 kristiansvalland