-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathjson.go
60 lines (51 loc) · 1.08 KB
/
json.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
/*
Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/
package goquutil
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
)
// JSONEncoder is convenience function for writing JSON values to db
func JSONEncoder(i interface{}) driver.Valuer {
return jsonEncoder{i}
}
// JSONDecoder is convenience function for reading JSON values from db
func JSONDecoder(i interface{}) sql.Scanner {
return jsonDecoder{i}
}
type jsonEncoder struct {
i interface{}
}
func (j jsonEncoder) Value() (driver.Value, error) {
b, err := json.Marshal(j.i)
if err != nil {
return nil, fmt.Errorf("marshal: %w", err)
}
return b, nil
}
type jsonDecoder struct {
i interface{}
}
func (j jsonDecoder) Scan(dest interface{}) error {
if dest == nil {
return errors.New("nil value")
}
var b []byte
switch s := dest.(type) {
case string:
b = []byte(s)
case []byte:
b = s
default:
return fmt.Errorf("expected '[]byte' or 'string' got %T", dest)
}
if err := json.Unmarshal(b, &j.i); err != nil {
return fmt.Errorf("unmarshal: %w", err)
}
return nil
}