-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathint.go
56 lines (50 loc) · 1.25 KB
/
int.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"
)
// Int64 is a possibly invalid int64 type.
type Int64 struct {
sql.NullInt64
}
// ValidInt64 returns a new Int64 that is valid.
func ValidInt64(value int64) Int64 {
return Int64{sql.NullInt64{Int64: value, Valid: true}}
}
// InvalidInt64 returns a new Int64 that is invalid.
func InvalidInt64() Int64 {
return Int64{sql.NullInt64{Int64: 0, Valid: false}}
}
// MarshalJSON converts a Int64 to JSON. It returns the value if valid and null
// otherwise.
func (null Int64) MarshalJSON() ([]byte, error) {
if null.Valid {
return json.Marshal(null.Int64)
}
return []byte("null"), nil
}
// UnmarshalJSON converts JSON to a Int64. Nil input returns an invalid Int64,
// otherwise it returns a valid Int64.
func (null *Int64) UnmarshalJSON(data []byte) error {
// Unmarshal
var value interface{}
if err := json.Unmarshal(data, &value); err != nil {
return err
}
switch value.(type) {
case int64:
null.Int64 = value.(int64)
null.Valid = true
case float64:
null.Int64 = int64(value.(float64))
null.Valid = true
case nil:
null.Int64 = 0
null.Valid = false
default:
return fmt.Errorf("Cannot unmarshal %v into sql.NullInt64", reflect.TypeOf(value).Name())
}
return nil
}