2018-12-31 22:01:16 +00:00
|
|
|
// Package json provides a json codec
|
|
|
|
package json
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io"
|
|
|
|
|
2019-06-09 11:50:50 +08:00
|
|
|
"github.com/golang/protobuf/jsonpb"
|
|
|
|
"github.com/golang/protobuf/proto"
|
2020-07-27 13:22:00 +01:00
|
|
|
"github.com/micro/go-micro/v3/codec"
|
2018-12-31 22:01:16 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Codec struct {
|
2019-06-09 11:55:36 +08:00
|
|
|
Conn io.ReadWriteCloser
|
|
|
|
Encoder *json.Encoder
|
|
|
|
Decoder *json.Decoder
|
2018-12-31 22:01:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) ReadHeader(m *codec.Message, t codec.MessageType) error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) ReadBody(b interface{}) error {
|
2019-01-10 22:14:32 +00:00
|
|
|
if b == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2019-06-09 11:50:50 +08:00
|
|
|
if pb, ok := b.(proto.Message); ok {
|
2019-06-09 11:55:36 +08:00
|
|
|
return jsonpb.UnmarshalNext(c.Decoder, pb)
|
2019-06-09 11:50:50 +08:00
|
|
|
}
|
2018-12-31 22:01:16 +00:00
|
|
|
return c.Decoder.Decode(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) Write(m *codec.Message, b interface{}) error {
|
2019-01-10 22:14:32 +00:00
|
|
|
if b == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2018-12-31 22:01:16 +00: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 11:55:36 +08:00
|
|
|
Conn: c,
|
|
|
|
Decoder: json.NewDecoder(c),
|
|
|
|
Encoder: json.NewEncoder(c),
|
2018-12-31 22:01:16 +00:00
|
|
|
}
|
|
|
|
}
|