forked from potato2003/actioncable-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannel_identifier.go
70 lines (56 loc) · 1.56 KB
/
channel_identifier.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
package actioncable
import (
"encoding/json"
"reflect"
)
type ChannelIdentifier struct {
channelName string
params map[string]interface{}
marshaledValue []byte
}
func NewChannelIdentifier(channelName string, params map[string]interface{}) *ChannelIdentifier {
if params == nil {
params = make(map[string]interface{})
}
id := &ChannelIdentifier{
channelName:channelName,
params:params,
}
m, _ := id.MarshalJSON()
id.marshaledValue = m
return id
}
// Implements json.Marshaler#MarshalJSON()
func (c *ChannelIdentifier) MarshalJSON() ([]byte, error) {
copied := make(map[string]interface{})
for k, v := range c.params {
copied[k] = v
}
copied["channel"] = c.channelName
return json.Marshal(copied)
}
// Implements json.Marshaler#UnmarshalJSON()
func (c *ChannelIdentifier) UnmarshalJSON(doubleEncodedData []byte) error {
str := ""
if err := json.Unmarshal(doubleEncodedData, &str); err != nil {
return err
}
raw := json.RawMessage(str)
params := make(map[string]interface{})
if err := json.Unmarshal(raw, ¶ms); err != nil {
return err
}
if str, ok := params["channel"].(string); ok {
c.channelName = str
}
delete(params, "channel")
c.params = params
c.marshaledValue = []byte(str)
return nil
}
func (self *ChannelIdentifier) Equals(other *ChannelIdentifier) bool {
// Comapre serialized value of self and other value.
// because golang does not support comparisons between Structs,
// so does not work when ChannelIdentifer#params including Struct Type.
return reflect.DeepEqual(self.marshaledValue, other.marshaledValue)
}