dbr/types.go

71 lines
1.4 KiB
Go

package dbr
import (
"database/sql"
"encoding/json"
"git.bit5.ru/backend/mysql"
)
//
// Your app can use these Null types instead of the defaults. The sole benefit you get is a MarshalJSON method that is not retarded.
//
// NullString is a type that can be null or a string
type NullString struct {
sql.NullString
}
// NullInt64 is a type that can be null or an int
type NullInt64 struct {
sql.NullInt64
}
// NullTime is a type that can be null or a time
type NullTime struct {
mysql.NullTime
}
// NullBool is a type that can be null or a bool
type NullBool struct {
sql.NullBool
}
var nullString = []byte("null")
// MarshalJSON correctly serializes a NullString to JSON
func (n *NullString) MarshalJSON() ([]byte, error) {
if n.Valid {
j, e := json.Marshal(n.String)
return j, e
}
return nullString, nil
}
// MarshalJSON correctly serializes a NullInt64 to JSON
func (n *NullInt64) MarshalJSON() ([]byte, error) {
if n.Valid {
j, e := json.Marshal(n.Int64)
return j, e
}
return nullString, nil
}
// MarshalJSON correctly serializes a NullTime to JSON
func (n *NullTime) MarshalJSON() ([]byte, error) {
if n.Valid {
j, e := json.Marshal(n.Time)
return j, e
}
return nullString, nil
}
// MarshalJSON correctly serializes a NullBool to JSON
func (n *NullBool) MarshalJSON() ([]byte, error) {
if n.Valid {
j, e := json.Marshal(n.Bool)
return j, e
}
return nullString, nil
}