-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurn.go
88 lines (73 loc) · 1.74 KB
/
urn.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package schema
import (
"database/sql/driver"
"fmt"
"github.com/leodido/go-urn"
)
// URN is an alias to https://github.com/leodido/go-urn.URN
type URN struct {
value *urn.URN
}
// NewURN creates a new urn
func NewURN(namespace, key string) *URN {
input := []byte("urn:" + namespace + ":" + key)
// parse the value
value, err := urn.NewMachine().Parse(input)
if err != nil {
panic(err)
}
return &URN{value: value}
}
// URNFromString parses a URN from string
func URNFromString(text string) (*URN, error) {
value, err := urn.NewMachine().Parse([]byte(text))
if err != nil {
return nil, err
}
return &URN{value: value}, nil
}
// URNFromBytes parses a URN from bytes
func URNFromBytes(data []byte) (*URN, error) {
value, err := urn.NewMachine().Parse(data)
if err != nil {
return nil, err
}
return &URN{value: value}, nil
}
// String returns the urn as string
func (u *URN) String() string {
// return the resource
return u.value.String()
}
// Namespace returns the namespace
func (u *URN) Namespace() string {
return u.value.ID
}
// Key returns the namespace key
func (u *URN) Key() string {
return u.value.SS
}
// Value implements the driver.Valuer interface.
func (u *URN) Value() (driver.Value, error) {
return u.String(), nil
}
// Scan implements the sql.Scanner interface.
// A 16-byte slice will be handled by UnmarshalBinary, while
// a longer byte slice or a string will be handled by UnmarshalText.
func (u *URN) Scan(input interface{}) error {
switch value := input.(type) {
case *URN:
// replace the value
*u = *value
case string:
key, err := URNFromString(value)
if err != nil {
return err
}
// replace the value
*u = *key
default:
return fmt.Errorf("schema: cannot convert %T to URN", input)
}
return nil
}