In Go Lang Set a tag for the whole structure.

I use Go and GoRestful to program the RESTFUL interface for some objects stored in the Google App Engine datastore.

The data is converted to JSON / XML and presented to the user with tags that control the style for each format. How can I also apply tags to the name of the structure itself, so it is displayed using the correct style?

An example of my structures:

type Shallow struct {
    Key          string    `datastore:"-" json:"key" xml:"key"`
    LastModified time.Time `json:"last_modified" xml:"last-modified"`
    Version      int       `json:"version" xml:"version"`
    Status       int       `json:"status" xml:"status"`
    Link         Link      `datastore:"-" json:"link" xml:"link"`
    Name         string    `json:"name" xml:"name"`
}

type ProbabilityEntry struct {
    ItemId      int64   `datastore:"ItemId" json:"item_id" xml:"item-id"`
    Probability float32 `datastore:"Probability" json:"probability" xml:"probability"`
    Quantity    int16   `datastore:"Quantity" json:"quantity" xml:"quantity"`
}

type LootTable struct {
    Shallow
    AllowPreload  bool               `json:"allow_preload" xml:"allow-preload"`
    Probabilities []ProbabilityEntry `json:"probabilities" xml:"probabilities"`
}

When a LootTable structure is sent in JSON / XML, it should represent itself as "loot_table" or "loot-table", not "LootTable".

+4
source share
1 answer

Simple answer:

:

type Payload struct {
   Loot LootTable `json:"loot_table"`
}

:

JSON , , . JSON API Response, , . :

type JSONResponse struct {
   Obj    interface{} `json:"obj"`    // Marshall'ed JSON (not wrapped)
   Type   string      `json:"type"`   // "loot_table" for example
   Ok     bool        `json:"ok"`     // Does this response require error handling?
   Errors []string    `json:"errors"` // Any errors, you could leave out Ok and just check this
}

, API , , , .

+4

All Articles