mysql.NullTime ã JSON ã«å¤æåºæ¥ãããã«ããã
ãããã¼
package main import ( "github.com/go-sql-driver/mysql" ) type Pigeon struct { LastFlewAt mysql.NullTime `json:"last_flew_at"` }
ã¿ãããªãã¨ãããã¨ããæ®éã« mysql drvicer çã§ä½¿ã£ã¦ãã¨ãããããã¨ã¯èµ·ãããªããã© gorp ã¨ã使ã£ã¦ãã¨è¾ãæãã«ãªã£ã¦å°ãããã¼ã
ãªã®ã§ JSON ã«å¤æå¯è½ãª NullTime ã®ã©ãã struct ãç¨æãã¦ããã¾ãããããçããèªç±ã«ä½¿ã£ã¦ãã ãããã³ã¼ãã®ã©ã¤ã»ã³ã¹ã¯ãããªãã¯ãã¡ã¤ã³ã§ãã
import ( "bytes" "github.com/go-sql-driver/mysql" "time" ) type NullTime struct { mysql.NullTime } func (nt NullTime) MarshalJSON() ([]byte, error) { if nt.Valid { return nt.Time.MarshalJSON() } else { return []byte("null"), nil } } func (nt *NullTime) UnmarshalJSON(data []byte) error { if bytes.Compare(data, []byte("null")) == 0 { nt.Valid = false return nil } t := time.Now() err := t.UnmarshalJSON(data) if err != nil { return err } nt.Valid = true nt.Time = t return nil }
åºæ¥ããããã¼