Created
May 18, 2018 01:56
-
-
Save khawerrind/ecad687303cb7b4b7fc83d943cf54398 to your computer and use it in GitHub Desktop.
Go MGO custom time struct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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