2019-01-01 01:01:16 +03:00
|
|
|
// Package json provides a json codec
|
|
|
|
package json
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io"
|
2020-08-25 15:41:48 +03:00
|
|
|
"io/ioutil"
|
2019-01-01 01:01:16 +03:00
|
|
|
|
2020-08-19 17:47:17 +03:00
|
|
|
"github.com/unistack-org/micro/v3/codec"
|
2020-08-25 15:41:48 +03:00
|
|
|
jsonpb "google.golang.org/protobuf/encoding/protojson"
|
|
|
|
"google.golang.org/protobuf/proto"
|
2019-01-01 01:01:16 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type Codec struct {
|
2019-06-09 06:55:36 +03:00
|
|
|
Conn io.ReadWriteCloser
|
|
|
|
Encoder *json.Encoder
|
|
|
|
Decoder *json.Decoder
|
2019-01-01 01:01:16 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) ReadHeader(m *codec.Message, t codec.MessageType) error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) ReadBody(b interface{}) error {
|
2019-01-11 01:14:32 +03:00
|
|
|
if b == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2020-10-16 09:38:57 +03:00
|
|
|
switch m := b.(type) {
|
|
|
|
case proto.Message:
|
2020-08-25 15:41:48 +03:00
|
|
|
buf, err := ioutil.ReadAll(c.Conn)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-10-16 09:38:57 +03:00
|
|
|
return jsonpb.Unmarshal(buf, m)
|
2019-06-09 06:50:50 +03:00
|
|
|
}
|
2019-01-01 01:01:16 +03:00
|
|
|
return c.Decoder.Decode(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) Write(m *codec.Message, b interface{}) error {
|
2019-01-11 01:14:32 +03:00
|
|
|
if b == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2019-01-01 01:01:16 +03:00
|
|
|
return c.Encoder.Encode(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) Close() error {
|
|
|
|
return c.Conn.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) String() string {
|
|
|
|
return "json"
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCodec(c io.ReadWriteCloser) codec.Codec {
|
|
|
|
return &Codec{
|
2019-06-09 06:55:36 +03:00
|
|
|
Conn: c,
|
|
|
|
Decoder: json.NewDecoder(c),
|
|
|
|
Encoder: json.NewEncoder(c),
|
2019-01-01 01:01:16 +03:00
|
|
|
}
|
|
|
|
}
|