git.zd.zone/hrpc/hrpc@v0.0.12/types/timestamp.go (about) 1 package types 2 3 import ( 4 "bytes" 5 "database/sql/driver" 6 "errors" 7 "fmt" 8 "reflect" 9 "strconv" 10 "time" 11 12 "go.mongodb.org/mongo-driver/bson" 13 "go.mongodb.org/mongo-driver/bson/bsontype" 14 ) 15 16 type Timestamp struct { 17 time.Time 18 } 19 20 func (t Timestamp) Value() (driver.Value, error) { 21 return t.Unix(), nil 22 } 23 24 func (t *Timestamp) Scan(src interface{}) error { 25 v, ok := src.(int64) 26 if !ok { 27 return errors.New( 28 "bad int64 type assertion, got name: " + reflect.TypeOf(src).Name() + " kind: " + reflect.TypeOf(src).Kind().String(), 29 ) 30 } 31 *t = Timestamp{time.Unix(v, 0)} 32 return nil 33 } 34 35 func (t Timestamp) MarshalJSON() ([]byte, error) { 36 return []byte(fmt.Sprintf("%d", t.Unix())), nil 37 } 38 39 func (t *Timestamp) UnmarshalJSON(data []byte) error { 40 s := string(bytes.Trim(data, "\"")) 41 v, err := strconv.ParseInt(s, 10, 64) 42 if err != nil { 43 return err 44 } 45 var nt = Timestamp{ 46 Time: time.Unix(v, 0), 47 } 48 *t = nt 49 return nil 50 } 51 52 func (t Timestamp) MarshalBSONValue() (bsontype.Type, []byte, error) { 53 return bson.MarshalValue(t.Time) 54 } 55 56 func (t *Timestamp) UnmarshalBSONValue(bType bsontype.Type, data []byte) error { 57 rv := bson.RawValue{Type: bType, Value: data} 58 return rv.Unmarshal(&t.Time) 59 }