forked from hyperworks/go-getstream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslug.go
94 lines (76 loc) · 1.54 KB
/
slug.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
89
90
91
92
93
94
package getstream
import (
"encoding/json"
"fmt"
"strings"
)
type Slug struct {
Slug, ID, Token string
}
func (s Slug) Valid() bool {
return s.Slug != "" && s.ID != ""
}
// Signature syntax is slug+id _without_ the colon, then the token.
func (s Slug) Signature() string {
return s.Slug + s.ID + " " + s.Token
}
func (s Slug) WithToken(token string) Slug {
return Slug{s.Slug, s.ID, token}
}
func (s Slug) MarshalJSON() ([]byte, error) {
str := s.Slug + ":" + s.ID
if s.Token != "" {
str += " " + s.Token
}
return json.Marshal(str)
}
func (s *Slug) UnmarshalJSON(bytes []byte) error {
var raw interface{}
if e := json.Unmarshal(bytes, &raw); e != nil {
return e
}
parseArr := func(parts []string) bool {
switch len(parts) {
case 1:
if parts = strings.Split(parts[0], ":"); len(parts) != 2 {
return false
}
case 2:
s.Token = parts[1]
if parts = strings.Split(parts[0], ":"); len(parts) != 2 {
return false
}
default:
return false
}
s.Slug, s.ID = parts[0], parts[1]
return true
}
Outer:
switch r := raw.(type) {
case string:
if parseArr(strings.Split(r, " ")) {
return nil
}
case []interface{}:
parts := make([]string, len(r), cap(r))
for i, iface := range r {
if str, ok := iface.(string); ok {
parts[i] = str
} else {
break Outer
}
}
if parseArr(parts) {
return nil
}
}
return fmt.Errorf("cannot parse slug from: %#v", raw)
}
func (s Slug) String() string {
result := s.Slug + ":" + s.ID
if s.Token != "" {
result += " " + s.Token
}
return result
}