Format Gorm struct to proper JSON

You could extract the fields in question to a separate struct and embed it, similar to what gorm is doing, if you’re going to be doing this in many types.

type commonModelFields struct {
	ID          uint       `gorm:"primary_key" json:"id"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
	DeletedAt   *time.Time `json:"deleted_at"`
}

type Cohort struct {
    commonModelFields
	Name        string     `gorm:"type:varchar(40); unique_index; not null" json:"name"`
	Description string     `gorm:"type:varchar(255); not null" json:"description"`
	Users       []User     `json:"users,omitempty"`
}

But I don’t think there’s anything wrong with the other way either.

1 Like