Skip to content

Instantly share code, notes, and snippets.

@roothybrid7
Last active December 6, 2015 02:06
Show Gist options
  • Save roothybrid7/a9357f89bac57c6470c4 to your computer and use it in GitHub Desktop.
Save roothybrid7/a9357f89bac57c6470c4 to your computer and use it in GitHub Desktop.
Golangのgormで、カスタマイズしたtime.Timeに差し変える ref: http://qiita.com/roothybrid7/items/52623bedb45ff0c26a8a
// gorm.Model
type Model struct {
ID uint64 `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
}
// Time Format
const (
RFC3339 = "2006-01-02T15:04:05Z07:00"
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
)
// JSON Encode
func (t Time) MarshalJSON() ([]byte, error) {
if y := t.Year(); y < 0 || y >= 10000 {
// RFC 3339 is clear that years are 4 digits exactly.
// See golang.org/issue/4556#c15 for more discussion.
return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
}
return []byte(t.Format(`"` + RFC3339Nano + `"`)), nil
}
type Model struct {
ID uint64 `gorm:"primary_key"`
CreatedAt ResourceTime `json:"createdAt"`
UpdatedAt ResourceTime `json:"updatedAt"`
DeletedAt *time.Time `json:"deletedAt,omitempty"`
}
package typedef
import (
"database/sql/driver"
"errors"
"time"
)
// XXX: アプリでナノ秒は必要ないので秒まででフォーマット
//{
// "createdAt": "2015-08-09T15:03:05.135166971Z",
// "objectID": "55c112a40000a1"
//}
// See: http://qiita.com/taizo/items/2c3a338f1aeea86ce9e2
type ResourceTime struct {
time.Time
}
func (rt ResourceTime) MarshalJSON() ([]byte, error) {
t := rt.Time
if y := t.Year(); y < 0 || y >= 10000 {
return nil, errors.New("ResourceTime.MarshalJSON: year outside of range [0,9999]")
}
return []byte(t.Format(`"` + time.RFC3339 + `"`)), nil
}
func (rt ResourceTime) MarshalText() ([]byte, error) {
t := rt.Time
if y := t.Year(); y < 0 || y >= 10000 {
return nil, errors.New("Time.MarshalText: year outside of range [0,9999]")
}
return []byte(t.Format(time.RFC3339)), nil
}
// Sql driver interface
func (rt *ResourceTime) Scan(value interface{}) error {
rt.Time = value.(time.Time)
return nil
}
func (rt ResourceTime) Value() (driver.Value, error) {
return rt.Time, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment