-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcodec.go
112 lines (92 loc) · 2.1 KB
/
codec.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package cable
import (
"fmt"
"io/ioutil"
"github.com/golang/protobuf/proto"
"github.com/gorilla/websocket"
"github.com/vmihailenco/msgpack/v5"
pb "github.com/anycable/xk6-cable/ac_protos"
)
type Codec struct {
Receive func(*websocket.Conn, interface{}) error
Send func(*websocket.Conn, interface{}) error
}
var JSONCodec = &Codec{
Receive: func(c *websocket.Conn, v interface{}) error {
return c.ReadJSON(v)
},
Send: func(c *websocket.Conn, v interface{}) error {
return c.WriteJSON(v)
},
}
var MsgPackCodec = &Codec{
Receive: func(c *websocket.Conn, v interface{}) error {
_, r, err := c.NextReader()
if err != nil {
return err
}
enc := msgpack.NewDecoder(r)
enc.SetCustomStructTag("json")
return enc.Decode(v)
},
Send: func(c *websocket.Conn, v interface{}) error {
w, err := c.NextWriter(websocket.BinaryMessage)
if err != nil {
return err
}
enc := msgpack.NewEncoder(w)
enc.SetCustomStructTag("json")
err1 := enc.Encode(v)
err2 := w.Close()
if err1 != nil {
return err1
}
return err2
},
}
var ProtobufCodec = &Codec{
Receive: func(c *websocket.Conn, v interface{}) error {
mtype, r, err := c.NextReader()
if err != nil {
return err
}
if mtype != websocket.BinaryMessage {
return fmt.Errorf("Unexpected message type: %v", mtype)
}
raw, err := ioutil.ReadAll(r)
if err != nil {
return err
}
buf := &pb.Message{}
if err := proto.Unmarshal(raw, buf); err != nil {
return err
}
msg := (v).(*cableMsg)
msg.Type = buf.Type.String()
msg.Identifier = buf.Identifier
if buf.Message != nil {
var message interface{}
err = msgpack.Unmarshal(buf.Message, &message)
msg.Message = message
}
return nil
},
Send: func(c *websocket.Conn, v interface{}) error {
msg := (v).(*cableMsg)
buf := &pb.Message{}
buf.Command = pb.Command(pb.Command_value[msg.Command])
buf.Identifier = msg.Identifier
buf.Data = msg.Data
b, err := proto.Marshal(buf)
if err != nil {
return err
}
w, err := c.NextWriter(websocket.BinaryMessage)
if err != nil {
return err
}
w.Write(b)
err = w.Close()
return err
},
}