Пример #1
0
func (c *Codec) ReadHeader(hdr *rpc.Header) error {
	c.msg = inMsg{} // avoid any potential cross-message contamination.
	var err error
	if c.isLogging() {
		var m json.RawMessage
		err = c.conn.Receive(&m)
		if err == nil {
			logger.Tracef("<- %s", m)
			err = json.Unmarshal(m, &c.msg)
		} else {
			logger.Tracef("<- error: %v (closing %v)", err, c.isClosing())
		}
	} else {
		err = c.conn.Receive(&c.msg)
	}
	if err != nil {
		// If we've closed the connection, we may get a spurious error,
		// so ignore it.
		if c.isClosing() || err == io.EOF {
			return io.EOF
		}
		return fmt.Errorf("error receiving message: %v", err)
	}
	hdr.RequestId = c.msg.RequestId
	hdr.Request = rpc.Request{
		Type:   c.msg.Type,
		Id:     c.msg.Id,
		Action: c.msg.Request,
	}
	hdr.Error = c.msg.Error
	hdr.ErrorCode = c.msg.ErrorCode
	return nil
}
Пример #2
0
func (c *testCodec) WriteMessage(hdr *rpc.Header, x interface{}) error {
	if reflect.ValueOf(x).Kind() != reflect.Struct {
		panic(fmt.Errorf("WriteRequest bad param; want struct got %T (%#v)", x, x))
	}
	if c.role != roleBoth && hdr.IsRequest() != (c.role == roleClient) {
		panic(fmt.Errorf("codec role %v; header wrong type %#v", c.role, hdr))
	}
	logger.Infof("send header: %#v; body: %#v", hdr, x)
	return c.Codec.WriteMessage(hdr, x)
}
Пример #3
0
func (c *testCodec) ReadHeader(hdr *rpc.Header) error {
	err := c.Codec.ReadHeader(hdr)
	if err != nil {
		return err
	}
	logger.Infof("got header %#v", hdr)
	if c.role != roleBoth && hdr.IsRequest() == (c.role == roleClient) {
		panic(fmt.Errorf("codec role %v; read wrong type %#v", c.role, hdr))
	}
	return nil
}
Пример #4
0
// init fills out the receiving outMsg with information from the given
// header and body.
func (m *outMsg) init(hdr *rpc.Header, body interface{}) {
	m.RequestId = hdr.RequestId
	m.Type = hdr.Request.Type
	m.Id = hdr.Request.Id
	m.Request = hdr.Request.Action
	m.Error = hdr.Error
	m.ErrorCode = hdr.ErrorCode
	if hdr.IsRequest() {
		m.Params = body
	} else {
		m.Response = body
	}
}
Пример #5
0
func (*suite) TestRead(c *gc.C) {
	for i, test := range readTests {
		c.Logf("test %d", i)
		codec := jsoncodec.New(&testConn{
			readMsgs: []string{test.msg},
		})
		var hdr rpc.Header
		err := codec.ReadHeader(&hdr)
		c.Assert(err, gc.IsNil)
		c.Assert(hdr, gc.DeepEquals, test.expectHdr)

		c.Assert(hdr.IsRequest(), gc.Equals, test.expectHdr.IsRequest())

		body := reflect.New(reflect.ValueOf(test.expectBody).Type().Elem()).Interface()
		err = codec.ReadBody(body, test.expectHdr.IsRequest())
		c.Assert(err, gc.IsNil)
		c.Assert(body, gc.DeepEquals, test.expectBody)

		err = codec.ReadHeader(&hdr)
		c.Assert(err, gc.Equals, io.EOF)
	}
}