forked from juju/juju
/
conn.go
61 lines (48 loc) · 1.22 KB
/
conn.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
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package jsoncodec
import (
"encoding/json"
"net"
"golang.org/x/net/websocket"
)
// NewWebsocket returns an rpc codec that uses the given websocket
// connection to send and receive messages.
func NewWebsocket(conn *websocket.Conn) *Codec {
return New(wsJSONConn{conn})
}
type wsJSONConn struct {
conn *websocket.Conn
}
func (conn wsJSONConn) Send(msg interface{}) error {
return websocket.JSON.Send(conn.conn, msg)
}
func (conn wsJSONConn) Receive(msg interface{}) error {
return websocket.JSON.Receive(conn.conn, msg)
}
func (conn wsJSONConn) Close() error {
return conn.conn.Close()
}
// NewNet returns an rpc codec that uses the given net
// connection to send and receive messages.
func NewNet(conn net.Conn) *Codec {
return New(&netConn{
enc: json.NewEncoder(conn),
dec: json.NewDecoder(conn),
conn: conn,
})
}
type netConn struct {
enc *json.Encoder
dec *json.Decoder
conn net.Conn
}
func (conn *netConn) Send(msg interface{}) error {
return conn.enc.Encode(msg)
}
func (conn *netConn) Receive(msg interface{}) error {
return conn.dec.Decode(msg)
}
func (conn *netConn) Close() error {
return conn.conn.Close()
}