a-h / generate

Generates Go (golang) Structs from JSON schema.
MIT License
444 stars 137 forks source link

Support defaults via const and New() functions #66

Open rustysys-dev opened 4 years ago

rustysys-dev commented 4 years ago

based on the following JSONSchema I would like to propose the generation of a New() function.

{
  "definitions": {},
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://example.com/root.json",
  "type": "object",
  "title": "The Root Schema",
  "required": [
    "type",
    "data"
  ],
  "properties": {
    "type": {
      "$id": "#/properties/type",
      "type": "string",
      "title": "Type",
      "default": "notify_event",
      "examples": [
        "notify_event"
      ],
      "pattern": "^(.*)$"
    },
    "data": {
      "$id": "#/properties/data",
      "type": "object",
      "title": "Data",
      "required": [
        "resourceId",
        "type",
        "title",
        "content"
      ],
      "properties": {
        "resourceId": {
          "$id": "#/properties/data/properties/resourceId",
          "type": "string",
          "title": "Resourceid",
          "default": "",
          "examples": [
            "1a2s3d4f"
          ],
          "pattern": "^(.*)$"
        },
        "type": {
          "$id": "#/properties/data/properties/type",
          "type": "string",
          "title": "Type",
          "default": "rule",
          "examples": [
            "rule"
          ],
          "pattern": "^(.*)$"
        },
        "title": {
          "$id": "#/properties/data/properties/title",
          "type": "string",
          "title": "Title",
          "default": "",
          "examples": [
            "rule violation"
          ],
          "pattern": "^(.*)$"
        },
        "content": {
          "$id": "#/properties/data/properties/content",
          "type": "string",
          "title": "Content",
          "default": "",
          "examples": [
            "some explaination about rule violation"
          ],
          "pattern": "^(.*)$"
        }
      }
    }
  }
}

Proposed Output:

package main

const (
    defaultType     string = "notify_event"
    defaultDataType string = "rule"
)

type schema struct {
    Data theData `json:"data"`
    Type string  `json:"type"`
}

type data struct {
    Content    string `json:"content"`
    Resourceid string `json:"resourceId"`
    Title      string `json:"title"`
    Type       string `json:"type"`
}

func NewSchema() *schema {
    return &schema{
        Data: data{
            Content:    "",
            Resourceid: "",
            Title:      "",
            Type:       defaultDataType,
        },
        Type: defaultType,
    }
}

func NewData() *data {
    return &data{
        Content:    "",
        Resourceid: "",
        Title:      "",
        Type:       defaultDataType,
    }
}