Created
October 12, 2016 22:59
-
-
Save wrunk/4120273dfe73c3c22f9ad4cd6e76ce02 to your computer and use it in GitHub Desktop.
Golang JSON Custom Marshal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
In a fairly typical webapp data model you often want to send | |
the client different "views" of the data model. | |
Many database and caching tools require the base model to be quite | |
standard with json tags and types, so the following approach is | |
ideal: | |
Based on this blog post and SO question: | |
http://choly.ca/post/go-json-marshalling/ | |
http://stackoverflow.com/questions/23695479/format-timestamp-in-outgoing-json-in-golang | |
Note there are quirks with this method, so test throughly. Also define json names for each base field and | |
the override fields | |
*/ | |
type DataModel struct { | |
Created time.Time `json:"created"` | |
FirstName string `json:"first_name"` | |
LastName string `json:"last_name"` | |
Password string `json:"pw"` | |
} | |
func (d *DataModel) PublicJSON() []byte { | |
type Alias DataModel | |
bys, err := json.Marshal(&struct { | |
*Alias | |
Password string `json:"pw,omitempty"` | |
Created string `json:"created"` | |
}{ | |
Alias: (*Alias)(d), | |
Created: d.Format("2006-01-02"), | |
}) | |
if err != nil { | |
panic(err) | |
} | |
return bys | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment