Skip to content

Instantly share code, notes, and snippets.

@khawerrind
Created May 18, 2018 01:56
Show Gist options
  • Save khawerrind/ecad687303cb7b4b7fc83d943cf54398 to your computer and use it in GitHub Desktop.
Save khawerrind/ecad687303cb7b4b7fc83d943cf54398 to your computer and use it in GitHub Desktop.
Go MGO custom time struct
type BaseFields struct {
ID string `json:"id" bson:"_id"`
CreatedAt time.Time `json:"created_at" bson:"created_at"`
UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
DeletedAt DeletedAt `json:"deleted" bson:"deleted_at,omitempty"`
}
type DeletedAt struct {
time.Time `bson:",omitempty"`
}
func GetDeletedAt() (t DeletedAt) {
t.Time = time.Now()
return
}
func (doc DeletedAt) MarshalJSON() ([]byte, error) {
res := "true"
if doc.IsZero() {
res = "false"
}
return []byte(res), nil
}
func (doc *DeletedAt) UnmarshalJSON(data []byte) error {
if string(data) == "true" {
t := GetDeletedAt()
doc = &t
} else {
doc = &DeletedAt{}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment