-
Notifications
You must be signed in to change notification settings - Fork 0
/
uuid.go
69 lines (56 loc) · 1.09 KB
/
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
58
59
60
61
62
63
64
65
66
67
68
69
package types
import (
"errors"
"github.com/go-viper/mapstructure/v2"
"github.com/google/uuid"
"gopkg.in/yaml.v3"
)
type UUID uuid.UUID
var _ yaml.Marshaler = (*UUID)(nil)
var _ mapstructure.Unmarshaler = (*UUID)(nil)
func NewUUID() UUID {
return UUID(uuid.New())
}
func (u UUID) MarshalYAML() (interface{}, error) {
return uuid.UUID(u).String(), nil
}
func (u *UUID) UnmarshalYAML(value *yaml.Node) error {
id, err := uuid.Parse(value.Value)
if err != nil {
return err
}
*u = UUID(id)
return nil
}
func (u *UUID) DecodeMapstructure(value interface{}) error {
switch v := value.(type) {
case string:
id, err := uuid.Parse(v)
if err != nil {
return err
}
*u = UUID(id)
return nil
case UUID:
*u = v
return nil
default:
return errors.New("unsupported type for UUID")
}
}
func (u UUID) Bytes() []byte {
var b []byte
c := uuid.UUID(u)
b = append(b, c[:]...)
return b
}
func ParseUUID(s string) (UUID, error) {
id, err := uuid.Parse(s)
if err != nil {
return UUID{}, err
}
return UUID(id), nil
}
func (u UUID) String() string {
return uuid.UUID(u).String()
}