/
map.go
73 lines (66 loc) · 1.45 KB
/
map.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package slices
import (
"database/sql/driver"
"encoding/json"
"fmt"
)
// Map is a map[string]interface.
type Map map[string]interface{}
// Interface implements the nulls.nullable interface.
func (m Map) Interface() interface{} {
return map[string]interface{}(m)
}
// Scan implements the sql.Scanner interface.
// It allows to read the map from the database value.
func (m *Map) Scan(src interface{}) error {
var b []byte
switch t := src.(type) {
case nil:
return nil
case []byte:
b = t
case string:
b = []byte(t)
default:
return fmt.Errorf("scan source was not []byte nor string but %T", src)
}
err := json.Unmarshal(b, m)
if err != nil {
return err
}
return nil
}
// Value implements the driver.Valuer interface.
// It allows to convert the map to a driver.value.
func (m Map) Value() (driver.Value, error) {
b, err := json.Marshal(m)
if err != nil {
return nil, err
}
return string(b), nil
}
// UnmarshalJSON will unmarshall JSON value into
// the map representation of this value.
func (m *Map) UnmarshalJSON(b []byte) error {
var stuff map[string]interface{}
err := json.Unmarshal(b, &stuff)
if err != nil {
return err
}
if *m == nil {
*m = Map{}
}
for key, value := range stuff {
(*m)[key] = value
}
return nil
}
// UnmarshalText will unmarshall text value into
// the map representation of this value.
func (m Map) UnmarshalText(text []byte) error {
err := json.Unmarshal(text, &m)
if err != nil {
return err
}
return nil
}