github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/rpc/jsoncodec/conn.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package jsoncodec
     5  
     6  import (
     7  	"encoding/json"
     8  	"net"
     9  
    10  	"golang.org/x/net/websocket"
    11  )
    12  
    13  // NewWebsocket returns an rpc codec that uses the given websocket
    14  // connection to send and receive messages.
    15  func NewWebsocket(conn *websocket.Conn) *Codec {
    16  	return New(wsJSONConn{conn})
    17  }
    18  
    19  type wsJSONConn struct {
    20  	conn *websocket.Conn
    21  }
    22  
    23  func (conn wsJSONConn) Send(msg interface{}) error {
    24  	return websocket.JSON.Send(conn.conn, msg)
    25  }
    26  
    27  func (conn wsJSONConn) Receive(msg interface{}) error {
    28  	return websocket.JSON.Receive(conn.conn, msg)
    29  }
    30  
    31  func (conn wsJSONConn) Close() error {
    32  	return conn.conn.Close()
    33  }
    34  
    35  // NewNet returns an rpc codec that uses the given net
    36  // connection to send and receive messages.
    37  func NewNet(conn net.Conn) *Codec {
    38  	return New(&netConn{
    39  		enc:  json.NewEncoder(conn),
    40  		dec:  json.NewDecoder(conn),
    41  		conn: conn,
    42  	})
    43  }
    44  
    45  type netConn struct {
    46  	enc  *json.Encoder
    47  	dec  *json.Decoder
    48  	conn net.Conn
    49  }
    50  
    51  func (conn *netConn) Send(msg interface{}) error {
    52  	return conn.enc.Encode(msg)
    53  }
    54  
    55  func (conn *netConn) Receive(msg interface{}) error {
    56  	return conn.dec.Decode(msg)
    57  }
    58  
    59  func (conn *netConn) Close() error {
    60  	return conn.conn.Close()
    61  }