Unmarshalling JSON content from a a file using GO and generate .go files using the GO template package

497 views Asked by At

I am interested in reading a schemas(json formatted text file) and unmarshall it as schemas (for which i have some JSON structures defined in a .GO file) and For each type of structure in the Schema, I want to generate a corresponding .go file which has the code for performing CRUD operations using the template package (http://golang.org/pkg/text/template/) to generate these files.

Example of a structure in a schema file - {

type struct XYZ {
    Type         string                 `json:"type,omitempty"`
    ResourceType string                 `json:"resourceType,omitempty"`
    Links        map[string]string      `json:"links,omitempty"`

}

The text file has a JSON structured data which is something of this form -

{
        "type": "collection",
        "resourceType": "schema",
        "links": {
        "self": "…/v1/schemas",
        },
        "createTypes": { },
        "actions": { },
        "data": [ 86 items
        {
        "id": "schema",
        "type": "schema",
        "links": {
        "self": "/schemas/schema",
        "collection": "…/schemas",
        },
         ...

     }

}

Could somebody help me how could i possibly generate the code for these CRUD operations for different structs using the GO template package.

1

There are 1 answers

1
peterSO On

You might find go generate useful.


proposal: go generate

New go tool subcommand proposed for Go 1.4. Please see the design document and comment in this thread.

http://golang.org/s/go1.4-generate

-rob


Go generate: A Proposal

Introduction

The go build command automates the construction of Go programs but sometimes preliminary processing is required, processing that go build does not support. Motivating examples include:

  • yacc: generating .go files from yacc grammar (.y) files
  • protobufs: generating .pb.go files from protocol buffer definition (.proto) files
  • Unicode: generating tables from UnicodeData.txt
  • HTML: embedding .html files into Go source code
  • bindata: translating binary files such as JPEGs into byte arrays in Go source

There are other processing steps one can imagine:

  • string methods: generating String() string methods for types used as enumerated constants
  • macros: generating customized implementations given generalized packages, such as sort.Ints from ints

This proposal offers a design for smooth automation of such processing.