Generic approach for marshalling a struct's time.Time fields to JSON with custom formatting

Viewed 148

My data model defines multiple structs that all have two fields in common: a StartDate and an EndDate. I need those two fields to be formatted as 2018-09-21 in the marshalled JSON, therefore the structs implement the Marshaller interface:

type Results struct {
    Source     string    `json:"source"`
    StartDate  time.Time 
    EndDate    time.Time 
}

type WeightedResults struct {
    Source          string           `json:"source"`
    StartDate       time.Time        
    EndDate         time.Time        
}

func (r Results) MarshalJSON() ([]byte, error) {
    type Alias Results
    if equalDate(r.StartDate, r.EndDate) {
        return json.Marshal(&struct {
            Date string `json:"date"`
            Alias
        }{
            Date:  r.StartDate.Format(dateFormat),
            Alias: (Alias)(r),
        })
    }    
    return json.Marshal(&struct {
        StartDate string `json:"start_date"`
        EndDate   string `json:"end_date"`
        Alias
    }{
        StartDate: r.StartDate.Format("2006-01-02"),
        EndDate:   r.EndDate.Format("2006-01-02"),
        Alias:     (Alias)(r),
    })
}

func (r WeightedResults) MarshalJSON() ([]byte, error) {
    type Alias WeightedResults
    if equalDate(r.StartDate, r.EndDate) {
        return json.Marshal(&struct {
            Date string `json:"date"`
            Alias
        }{
            Date:  r.StartDate.Format(dateFormat),
            Alias: (Alias)(r),
        })
    } 
    return json.Marshal(&struct {
        StartDate string `json:"start_date"`
        EndDate   string `json:"end_date"`
        Alias
    }{
        StartDate: r.StartDate.Format("2006-01-02"),
        EndDate:   r.EndDate.Format("2006-01-02"),
        Alias:     (Alias)(r),
    })
}

The solution above works fine but yields lots of code duplication. Is there any way to refactor both implementations of MarshalJSON to use the same logic/code? I am well aware that Go does not offer Generics (yet), but there has to be another way around this issue, right?

1 Answers

Your custom marshaler should not be on the structs, but on a custom type that embeds time.Time:

type MyTime struct {
    time.Time
}

func (t MyTime) MarshalJSON() ([]byte, error) {
    return json.Marshal(t.Format("2006-01-02"))
}

Then use this type everywhere you want.

type Results struct {
    Source     string    `json:"source"`
    StartDate  MyTime
    EndDate    MyTime
}
Related