2020-11-03 01:27:13 +03:00
|
|
|
// Package json provides a json codec
|
|
|
|
package json
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io"
|
2020-11-24 16:28:10 +03:00
|
|
|
"io/ioutil"
|
2020-11-03 01:27:13 +03:00
|
|
|
|
|
|
|
"github.com/unistack-org/micro/v3/codec"
|
|
|
|
)
|
|
|
|
|
2020-11-24 16:28:10 +03:00
|
|
|
type jsonCodec struct{}
|
|
|
|
|
|
|
|
func (c *jsonCodec) Marshal(b interface{}) ([]byte, error) {
|
|
|
|
if b == nil {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
switch m := b.(type) {
|
|
|
|
case *codec.Frame:
|
|
|
|
return m.Data, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return json.Marshal(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *jsonCodec) Unmarshal(b []byte, v interface{}) error {
|
2020-11-25 12:22:51 +03:00
|
|
|
if b == nil || v == nil {
|
2020-11-24 16:28:10 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
switch m := v.(type) {
|
|
|
|
case *codec.Frame:
|
|
|
|
m.Data = b
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return json.Unmarshal(b, v)
|
2020-11-03 01:27:13 +03:00
|
|
|
}
|
|
|
|
|
2020-11-23 18:42:17 +03:00
|
|
|
func (c *jsonCodec) ReadHeader(conn io.ReadWriter, m *codec.Message, t codec.MessageType) error {
|
2020-11-03 01:27:13 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-11-23 18:42:17 +03:00
|
|
|
func (c *jsonCodec) ReadBody(conn io.ReadWriter, b interface{}) error {
|
2020-11-03 01:27:13 +03:00
|
|
|
if b == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2020-11-24 16:28:10 +03:00
|
|
|
switch m := b.(type) {
|
|
|
|
case *codec.Frame:
|
|
|
|
buf, err := ioutil.ReadAll(conn)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
m.Data = buf
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-11-23 18:42:17 +03:00
|
|
|
return json.NewDecoder(conn).Decode(b)
|
2020-11-03 01:27:13 +03:00
|
|
|
}
|
|
|
|
|
2020-11-23 18:42:17 +03:00
|
|
|
func (c *jsonCodec) Write(conn io.ReadWriter, m *codec.Message, b interface{}) error {
|
2020-11-03 01:27:13 +03:00
|
|
|
if b == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2020-11-24 16:28:10 +03:00
|
|
|
switch m := b.(type) {
|
|
|
|
case *codec.Frame:
|
|
|
|
_, err := conn.Write(m.Data)
|
|
|
|
return err
|
2020-11-23 18:42:17 +03:00
|
|
|
}
|
2020-11-03 01:27:13 +03:00
|
|
|
|
2020-11-24 16:28:10 +03:00
|
|
|
return json.NewEncoder(conn).Encode(b)
|
2020-11-23 18:42:17 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *jsonCodec) String() string {
|
2020-11-03 01:27:13 +03:00
|
|
|
return "json"
|
|
|
|
}
|
|
|
|
|
2020-11-23 18:42:17 +03:00
|
|
|
func NewCodec() codec.Codec {
|
|
|
|
return &jsonCodec{}
|
2020-11-03 01:27:13 +03:00
|
|
|
}
|