Ejemplo n.º 1
0
func (c *Codec) WriteMessage(hdr *rpc.Header, body interface{}) error {
	r := &outMsg{
		RequestId: hdr.RequestId,

		Type:    hdr.Type,
		Id:      hdr.Id,
		Request: hdr.Request,

		Error:     hdr.Error,
		ErrorCode: hdr.ErrorCode,
	}
	if hdr.IsRequest() {
		r.Params = body
	} else {
		r.Response = body
	}
	if c.isLogging() {
		data, err := json.Marshal(r)
		if err != nil {
			log.Debugf("rpc/jsoncodec: -> marshal error: %v", err)
			return err
		}
		log.Debugf("rpc/jsoncodec: -> %s", data)
	}
	return c.conn.Send(r)
}
Ejemplo n.º 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))
	}
	log.Infof("send header: %#v; body: %#v", hdr, x)
	return c.Codec.WriteMessage(hdr, x)
}
Ejemplo n.º 3
0
func (c *testCodec) ReadHeader(hdr *rpc.Header) error {
	err := c.Codec.ReadHeader(hdr)
	if err != nil {
		return err
	}
	log.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
}
Ejemplo n.º 4
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 {
			log.Debugf("rpc/jsoncodec: <- %s", m)
			err = json.Unmarshal(m, &c.msg)
		} else {
			log.Debugf("rpc/jsoncodec: <- 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.Type = c.msg.Type
	hdr.Id = c.msg.Id
	hdr.Request = c.msg.Request
	hdr.Error = c.msg.Error
	hdr.ErrorCode = c.msg.ErrorCode
	return nil
}
Ejemplo n.º 5
0
func (*suite) TestRead(c *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, IsNil)
		c.Assert(hdr, DeepEquals, test.expectHdr)

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

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

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