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 }
出来たポッポー