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) {
|
|
|
|
switch m := b.(type) {
|
2020-11-29 21:03:18 +03:00
|
|
|
case nil:
|
|
|
|
return nil, nil
|
2020-11-24 16:28:10 +03:00
|
|
|
case *codec.Frame:
|
|
|
|
return m.Data, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return json.Marshal(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *jsonCodec) Unmarshal(b []byte, v interface{}) error {
|
2020-11-29 21:03:18 +03:00
|
|
|
if b == nil {
|
2020-11-24 16:28:10 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
switch m := v.(type) {
|
2020-11-29 21:03:18 +03:00
|
|
|
case nil:
|
|
|
|
return nil
|
2020-11-24 16:28:10 +03:00
|
|
|
case *codec.Frame:
|
|
|
|
m.Data = b
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return json.Unmarshal(b, v)
|
2020-11-03 01:27:13 +03:00
|
|
|
}
|
|
|
|
|
2020-12-20 23:56:04 +03:00
|
|
|
func (c *jsonCodec) ReadHeader(conn io.Reader, m *codec.Message, t codec.MessageType) error {
|
2020-11-03 01:27:13 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-12-20 23:56:04 +03:00
|
|
|
func (c *jsonCodec) ReadBody(conn io.Reader, b interface{}) error {
|
2020-11-24 16:28:10 +03:00
|
|
|
switch m := b.(type) {
|
2020-11-29 21:03:18 +03:00
|
|
|
case nil:
|
|
|
|
return nil
|
2020-11-24 16:28:10 +03:00
|
|
|
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-12-20 23:56:04 +03:00
|
|
|
func (c *jsonCodec) Write(conn io.Writer, m *codec.Message, b interface{}) error {
|
2020-11-24 16:28:10 +03:00
|
|
|
switch m := b.(type) {
|
2020-11-29 21:03:18 +03:00
|
|
|
case nil:
|
|
|
|
return nil
|
2020-11-24 16:28:10 +03:00
|
|
|
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
|
|
|
}
|