From bfd22b1f3914113d5fa850aef03efdb227af6cb2 Mon Sep 17 00:00:00 2001 From: "Alexander A. Klimov" Date: Wed, 7 Apr 2021 11:56:39 +0200 Subject: [PATCH] Make types.Bool an encoding.TextUnmarshaler --- pkg/types/bool.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/pkg/types/bool.go b/pkg/types/bool.go index 9f8202c2..f711fd08 100644 --- a/pkg/types/bool.go +++ b/pkg/types/bool.go @@ -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) )