Handle marshaling of numbers and strings for channels

This commit is contained in:
Paul Tyng
2021-03-21 21:13:58 -04:00
parent 9c60a9de6f
commit 82a3baaf00
5 changed files with 171 additions and 10 deletions

View File

@@ -5,6 +5,32 @@ import (
"strings"
)
// numberOrString handles strings that can also accept JSON numbers.
// For example a field may contain a number or the string "auto".
type numberOrString string
func (e *numberOrString) UnmarshalJSON(b []byte) error {
if len(b) == 0 {
return nil
}
s := string(b)
if s == `""` {
*e = ""
return nil
}
var err error
if strings.HasPrefix(s, `"`) && strings.HasSuffix(s, `"`) {
s, err = strconv.Unquote(s)
if err != nil {
return err
}
*e = numberOrString(s)
return nil
}
*e = numberOrString(string(b))
return nil
}
// emptyStringInt was created due to the behavior change in
// Go 1.14 with json.Number's handling of empty string.
type emptyStringInt int
@@ -13,11 +39,12 @@ func (e *emptyStringInt) UnmarshalJSON(b []byte) error {
if len(b) == 0 {
return nil
}
if string(b) == `""` {
s := string(b)
if s == `""` {
*e = 0
return nil
}
var err error
s := string(b)
if strings.HasPrefix(s, `"`) && strings.HasSuffix(s, `"`) {
s, err = strconv.Unquote(s)
if err != nil {