Skip to content

Instantly share code, notes, and snippets.

@wrunk
Created October 12, 2016 22:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrunk/4120273dfe73c3c22f9ad4cd6e76ce02 to your computer and use it in GitHub Desktop.
Save wrunk/4120273dfe73c3c22f9ad4cd6e76ce02 to your computer and use it in GitHub Desktop.
Golang JSON Custom Marshal
/*
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