Make types.Bool an encoding.TextUnmarshaler

This commit is contained in:
Alexander A. Klimov 2021-04-07 11:56:39 +02:00
parent fb4fd4c964
commit bfd22b1f39

View file

@ -3,8 +3,10 @@ package types
import (
"database/sql"
"database/sql/driver"
"encoding"
"encoding/json"
"errors"
"strconv"
)
var (
@ -41,6 +43,17 @@ func (b Bool) MarshalJSON() ([]byte, error) {
return json.Marshal(b.Bool)
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (b *Bool) UnmarshalText(text []byte) error {
parsed, err := strconv.ParseUint(string(text), 10, 64)
if err != nil {
return err
}
*b = Bool{parsed != 0, true}
return nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (b *Bool) UnmarshalJSON(data []byte) error {
if string(data) == "null" || len(data) == 0 {
@ -95,8 +108,9 @@ func (b Bool) Value() (driver.Value, error) {
// Assert interface compliance.
var (
_ json.Marshaler = (*Bool)(nil)
_ json.Unmarshaler = (*Bool)(nil)
_ sql.Scanner = (*Bool)(nil)
_ driver.Valuer = (*Bool)(nil)
_ json.Marshaler = (*Bool)(nil)
_ encoding.TextUnmarshaler = (*Bool)(nil)
_ json.Unmarshaler = (*Bool)(nil)
_ sql.Scanner = (*Bool)(nil)
_ driver.Valuer = (*Bool)(nil)
)