-
Notifications
You must be signed in to change notification settings - Fork 1
/
float.go
56 lines (50 loc) · 1.31 KB
/
float.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package nulls
import (
"database/sql"
"encoding/json"
"fmt"
"reflect"
)
// Float64 is a possibly invalid float64 type.
type Float64 struct {
sql.NullFloat64
}
// ValidFloat64 returns a new Float64 that is valid.
func ValidFloat64(value float64) Float64 {
return Float64{sql.NullFloat64{Float64: value, Valid: true}}
}
// InvalidFloat64 returns a new Float64 that is invalid.
func InvalidFloat64() Float64 {
return Float64{sql.NullFloat64{Float64: 0, Valid: false}}
}
// MarshalJSON converts a Float64 to JSON. It returns the value if valid and null
// otherwise.
func (null Float64) MarshalJSON() ([]byte, error) {
if null.Valid {
return json.Marshal(null.Float64)
}
return []byte("null"), nil
}
// UnmarshalJSON converts JSON to a Float64. Nil input returns an invalid Float64,
// otherwise it returns a valid Float64.
func (null *Float64) UnmarshalJSON(data []byte) error {
// Unmarshal
var value interface{}
if err := json.Unmarshal(data, &value); err != nil {
return err
}
switch value.(type) {
case int64:
null.Float64 = float64(value.(int64))
null.Valid = true
case float64:
null.Float64 = value.(float64)
null.Valid = true
case nil:
null.Float64 = 0
null.Valid = false
default:
return fmt.Errorf("Cannot unmarshal %v into sql.NullFloat64", reflect.TypeOf(value).Name())
}
return nil
}