micro/codec/json/json.go
Vasiliy Tolstov 14c97d59c1 many improvements with options and noop stuff
* add many options helpers
* fix noop client to allow publish messages to topic in broker
* fix noop server to allow registering in registry
* fix noop server to allow subscribe to topic in broker
* fix new service initialization

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-16 09:38:57 +03:00

61 lines
1.0 KiB
Go

// Package json provides a json codec
package json
import (
"encoding/json"
"io"
"io/ioutil"
"github.com/unistack-org/micro/v3/codec"
jsonpb "google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
type Codec struct {
Conn io.ReadWriteCloser
Encoder *json.Encoder
Decoder *json.Decoder
}
func (c *Codec) ReadHeader(m *codec.Message, t codec.MessageType) error {
return nil
}
func (c *Codec) ReadBody(b interface{}) error {
if b == nil {
return nil
}
switch m := b.(type) {
case proto.Message:
buf, err := ioutil.ReadAll(c.Conn)
if err != nil {
return err
}
return jsonpb.Unmarshal(buf, m)
}
return c.Decoder.Decode(b)
}
func (c *Codec) Write(m *codec.Message, b interface{}) error {
if b == nil {
return nil
}
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{
Conn: c,
Decoder: json.NewDecoder(c),
Encoder: json.NewEncoder(c),
}
}