-
Notifications
You must be signed in to change notification settings - Fork 3
/
nullfloat.go
58 lines (47 loc) · 1.11 KB
/
nullfloat.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
57
58
package types
import (
"database/sql"
"encoding/json"
)
// NullFloat represents a float that can be null when marshalled to JSON
type NullFloat struct {
sql.NullFloat64
}
// Value returns the value of the NullFloat (even if it is invalid)
func (r *NullFloat) Value() float64 {
return r.Float64
}
// SetValue sets the value of the NullFloat
func (r *NullFloat) SetValue(v float64) {
r.Float64 = v
r.Valid = true
}
// IsValid returns true or false if the NullFloat is valid
func (r *NullFloat) IsValid() bool {
return r.Valid
}
// SetInvalid sets the NullFloat as invalid
func (r *NullFloat) SetInvalid() {
r.Valid = false
}
// MarshalJSON allows to marshal this struct into JSON
func (r NullFloat) MarshalJSON() ([]byte, error) {
var s interface{} = r.Float64
if r.Valid == false {
s = nil
}
return json.Marshal(s)
}
// UnmarshalJSON allows to marshal this struct into JSON
func (r *NullFloat) UnmarshalJSON(b []byte) error {
var float interface{}
if err := json.Unmarshal(b, &float); err != nil {
return err
}
if float == nil {
r.SetInvalid()
return nil
}
r.SetValue(float.(float64))
return nil
}