-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_uuid.go
57 lines (46 loc) · 1.22 KB
/
binary_uuid.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
package main
import (
"database/sql/driver"
"errors"
"fmt"
"github.com/google/uuid"
)
// BinaryUUID -> binary uuid wrapper over uuid.UUID
type BinaryUUID uuid.UUID
// ParseUUID -> parses string uuid to binary uuid
func ParseUUID(id string) BinaryUUID {
return BinaryUUID(uuid.MustParse(id))
}
func (b BinaryUUID) String() string {
return uuid.UUID(b).String()
}
// MarshalJSON -> convert to json string
func (b BinaryUUID) MarshalJSON() ([]byte, error) {
s := uuid.UUID(b)
str := "\"" + s.String() + "\""
return []byte(str), nil
}
// UnmarshalJSON -> convert from json string
func (b *BinaryUUID) UnmarshalJSON(by []byte) error {
s, err := uuid.ParseBytes(by)
*b = BinaryUUID(s)
return err
}
// GormDataType -> sql data type for gorm
func (BinaryUUID) GormDataType() string {
return "binary(16)"
}
// Scan -> scan value into BinaryUUID
func (b *BinaryUUID) Scan(value interface{}) error {
bytes, ok := value.([]byte)
if !ok {
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
}
data, err := uuid.FromBytes(bytes)
*b = BinaryUUID(data)
return err
}
// Value -> return BinaryUUID to []bytes binary(16)
func (b BinaryUUID) Value() (driver.Value, error) {
return uuid.UUID(b).MarshalBinary()
}