micro/codec/jsonrpc/jsonrpc.go

89 lines
1.6 KiB
Go
Raw Normal View History

2018-11-20 10:06:13 +00:00
// Package jsonrpc provides a json-rpc 1.0 codec
2015-11-28 18:54:38 +00:00
package jsonrpc
2015-11-28 18:40:32 +00:00
import (
"bytes"
"encoding/json"
"fmt"
"io"
"github.com/unistack-org/micro/v3/codec"
2015-11-28 18:40:32 +00:00
)
type jsonCodec struct {
buf *bytes.Buffer
mt codec.MessageType
rwc io.ReadWriteCloser
c *clientCodec
s *serverCodec
}
func (j *jsonCodec) Close() error {
j.buf.Reset()
return j.rwc.Close()
}
func (j *jsonCodec) String() string {
2015-11-28 18:54:38 +00:00
return "json-rpc"
2015-11-28 18:40:32 +00:00
}
func (j *jsonCodec) Write(m *codec.Message, b interface{}) error {
switch m.Type {
case codec.Request:
return j.c.Write(m, b)
2019-01-13 12:15:35 +00:00
case codec.Response, codec.Error:
2015-11-28 18:40:32 +00:00
return j.s.Write(m, b)
2019-07-07 12:44:09 +01:00
case codec.Event:
2015-11-28 18:40:32 +00:00
data, err := json.Marshal(b)
if err != nil {
return err
}
_, err = j.rwc.Write(data)
return err
default:
return fmt.Errorf("Unrecognised message type: %v", m.Type)
}
}
func (j *jsonCodec) ReadHeader(m *codec.Message, mt codec.MessageType) error {
j.buf.Reset()
j.mt = mt
switch mt {
case codec.Request:
return j.s.ReadHeader(m)
case codec.Response:
return j.c.ReadHeader(m)
2019-07-07 12:44:09 +01:00
case codec.Event:
2018-11-13 11:56:21 +03:00
_, err := io.Copy(j.buf, j.rwc)
return err
2015-11-28 18:40:32 +00:00
default:
return fmt.Errorf("Unrecognised message type: %v", mt)
}
}
func (j *jsonCodec) ReadBody(b interface{}) error {
switch j.mt {
case codec.Request:
return j.s.ReadBody(b)
case codec.Response:
return j.c.ReadBody(b)
2019-07-07 12:44:09 +01:00
case codec.Event:
2015-11-28 18:40:32 +00:00
if b != nil {
return json.Unmarshal(j.buf.Bytes(), b)
}
default:
return fmt.Errorf("Unrecognised message type: %v", j.mt)
}
return nil
}
func NewCodec(rwc io.ReadWriteCloser) codec.Codec {
return &jsonCodec{
buf: bytes.NewBuffer(nil),
rwc: rwc,
c: newClientCodec(rwc),
s: newServerCodec(rwc),
}
}