diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 12:36:04 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 12:36:04 +0000 |
commit | b09c6d56832eb1718c07d74abf3bc6ae3fe4e030 (patch) | |
tree | d2caec2610d4ea887803ec9e9c3cd77136c448ba /pkg/types/float.go | |
parent | Initial commit. (diff) | |
download | icingadb-upstream.tar.xz icingadb-upstream.zip |
Adding upstream version 1.1.0.upstream/1.1.0upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
-rw-r--r-- | pkg/types/float.go | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/pkg/types/float.go b/pkg/types/float.go new file mode 100644 index 0000000..a4aedd6 --- /dev/null +++ b/pkg/types/float.go @@ -0,0 +1,68 @@ +package types + +import ( + "bytes" + "database/sql" + "database/sql/driver" + "encoding" + "encoding/json" + "github.com/icinga/icingadb/internal" + "strconv" +) + +// Float adds JSON support to sql.NullFloat64. +type Float struct { + sql.NullFloat64 +} + +// MarshalJSON implements the json.Marshaler interface. +// Supports JSON null. +func (f Float) MarshalJSON() ([]byte, error) { + var v interface{} + if f.Valid { + v = f.Float64 + } + + return internal.MarshalJSON(v) +} + +// UnmarshalText implements the encoding.TextUnmarshaler interface. +func (f *Float) UnmarshalText(text []byte) error { + parsed, err := strconv.ParseFloat(string(text), 64) + if err != nil { + return internal.CantParseFloat64(err, string(text)) + } + + *f = Float{sql.NullFloat64{ + Float64: parsed, + Valid: true, + }} + + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface. +// Supports JSON null. +func (f *Float) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if bytes.HasPrefix(data, []byte{'n'}) { + return nil + } + + if err := internal.UnmarshalJSON(data, &f.Float64); err != nil { + return err + } + + f.Valid = true + + return nil +} + +// Assert interface compliance. +var ( + _ json.Marshaler = Float{} + _ encoding.TextUnmarshaler = (*Float)(nil) + _ json.Unmarshaler = (*Float)(nil) + _ driver.Valuer = Float{} + _ sql.Scanner = (*Float)(nil) +) |