-
Notifications
You must be signed in to change notification settings - Fork 0
/
orm.go
61 lines (55 loc) · 1.18 KB
/
orm.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
package utils
import (
"database/sql/driver"
"fmt"
"github.com/lazygophers/log"
"github.com/lazygophers/utils/json"
"reflect"
"github.com/mcuadros/go-defaults"
"github.com/pkg/errors"
)
func Scan(src interface{}, dst interface{}) (err error) {
x := func(buf []byte) error {
bufLen := len(buf)
if bufLen >= 2 && ((buf[0] == '{' && buf[bufLen-1] == '}') || (buf[0] == '[' && buf[bufLen-1] == ']')) {
err = json.Unmarshal(buf, dst)
if err != nil {
log.Errorf("err:%v", err)
return err
}
return nil
} else if bufLen > 0 {
err = json.Unmarshal(buf, dst)
if err != nil {
log.Errorf("err:%v", err)
return err
}
return nil
} else {
defaults.SetDefaults(dst)
}
return nil
}
switch r := src.(type) {
case []byte:
buf := src.([]byte)
return x(buf)
case string:
buf := []byte(src.(string))
return x(buf)
default:
return errors.New(
fmt.Sprintf("unknown type %v %s to scan", r, reflect.ValueOf(src).String()))
}
}
func Value(m interface{}) (value driver.Value, err error) {
if m == nil {
defaults.SetDefaults(m)
}
value, err = json.Marshal(m)
if err != nil {
log.Errorf("err:%v", err)
return nil, err
}
return value, nil
}