1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-18 08:26:38 +02:00
go-micro/codec/jsonrpc/jsonrpc.go

89 lines
1.6 KiB
Go
Raw Normal View History

2018-11-20 12:06:13 +02:00
// Package jsonrpc provides a json-rpc 1.0 codec
2015-11-28 20:54:38 +02:00
package jsonrpc
2015-11-28 20:40:32 +02:00
import (
"bytes"
"encoding/json"
"fmt"
"io"
2021-10-12 13:55:53 +02:00
"go-micro.dev/v4/codec"
2015-11-28 20:40:32 +02:00
)
type jsonCodec struct {
rwc io.ReadWriteCloser
2023-04-26 02:16:34 +02:00
buf *bytes.Buffer
2015-11-28 20:40:32 +02:00
c *clientCodec
s *serverCodec
2023-04-26 02:16:34 +02:00
mt codec.MessageType
2015-11-28 20:40:32 +02:00
}
func (j *jsonCodec) Close() error {
j.buf.Reset()
return j.rwc.Close()
}
func (j *jsonCodec) String() string {
2015-11-28 20:54:38 +02:00
return "json-rpc"
2015-11-28 20:40:32 +02: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 14:15:35 +02:00
case codec.Response, codec.Error:
2015-11-28 20:40:32 +02:00
return j.s.Write(m, b)
2019-07-07 13:44:09 +02:00
case codec.Event:
2015-11-28 20:40:32 +02:00
data, err := json.Marshal(b)
if err != nil {
return err
}
_, err = j.rwc.Write(data)
return err
default:
2022-09-30 16:27:07 +02:00
return fmt.Errorf("Unrecognized message type: %v", m.Type)
2015-11-28 20:40:32 +02:00
}
}
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 13:44:09 +02:00
case codec.Event:
2018-11-13 10:56:21 +02:00
_, err := io.Copy(j.buf, j.rwc)
return err
2015-11-28 20:40:32 +02:00
default:
2022-09-30 16:27:07 +02:00
return fmt.Errorf("Unrecognized message type: %v", mt)
2015-11-28 20:40:32 +02:00
}
}
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 13:44:09 +02:00
case codec.Event:
2015-11-28 20:40:32 +02:00
if b != nil {
return json.Unmarshal(j.buf.Bytes(), b)
}
default:
2022-09-30 16:27:07 +02:00
return fmt.Errorf("Unrecognized message type: %v", j.mt)
2015-11-28 20:40:32 +02:00
}
return nil
}
func NewCodec(rwc io.ReadWriteCloser) codec.Codec {
return &jsonCodec{
buf: bytes.NewBuffer(nil),
rwc: rwc,
c: newClientCodec(rwc),
s: newServerCodec(rwc),
}
}