Skip to content

Instantly share code, notes, and snippets.

@lummie
Created July 25, 2017 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lummie/7c4a4c273464b42242fa06f120d4b4de to your computer and use it in GitHub Desktop.
Save lummie/7c4a4c273464b42242fa06f120d4b4de to your computer and use it in GitHub Desktop.
Idiomatic way to extend a struct when marshalling to Json
package main
// This example shows how to extend a struct for marshalling, e.g. to Json to allow private fields
// to be exposed or for adding additonal fields that are populated at runtime.
import (
"encoding/json"
"fmt"
"time"
)
type Job struct {
Job string
Started time.Time
Finished time.Time
private string
}
func (j *Job) Duration() time.Duration {
if j.Finished.IsZero() {
return time.Since(j.Started)
} else {
return j.Finished.Sub(j.Started)
}
}
func (j *Job) MarshalJSON() ([]byte, error) {
// introduce a new temproary struct
type temp struct {
Job // Job as an anonymous field
Private string // this will be set to the job's private field
Duration string // this is a new field that will be the result of calling a function on the orginal job instance
}
t := temp{
*j, // our base job
j.private, // Sets Private to j.private
j.Duration().String(), //Sets the Duration to the result of a job.method
}
return json.Marshal(t)
}
func main() {
// create job
j := Job{
Job: "My Job",
Started: time.Now(),
Finished: time.Now().Add(10 * time.Second),
private: "private string",
}
// marshal to json
b, _ := json.Marshal(&j)
// print out json
fmt.Println(string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment