2020-11-30 23:40:08 +03:00
|
|
|
// Package yaml provides a yaml codec
|
|
|
|
package yaml
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
|
|
|
|
"github.com/ghodss/yaml"
|
|
|
|
"github.com/unistack-org/micro/v3/codec"
|
|
|
|
)
|
|
|
|
|
|
|
|
type yamlCodec struct{}
|
|
|
|
|
|
|
|
func (c *yamlCodec) Marshal(b interface{}) ([]byte, error) {
|
|
|
|
switch m := b.(type) {
|
|
|
|
case nil:
|
|
|
|
return nil, nil
|
|
|
|
case *codec.Frame:
|
|
|
|
return m.Data, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return yaml.Marshal(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *yamlCodec) Unmarshal(b []byte, v interface{}) error {
|
2021-04-12 19:20:17 +03:00
|
|
|
if len(b) == 0 {
|
2020-11-30 23:40:08 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
switch m := v.(type) {
|
|
|
|
case nil:
|
|
|
|
return nil
|
|
|
|
case *codec.Frame:
|
|
|
|
m.Data = b
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return yaml.Unmarshal(b, v)
|
|
|
|
}
|
|
|
|
|
2020-12-21 00:02:24 +03:00
|
|
|
func (c *yamlCodec) ReadHeader(conn io.Reader, m *codec.Message, t codec.MessageType) error {
|
2020-11-30 23:40:08 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-12-21 00:02:24 +03:00
|
|
|
func (c *yamlCodec) ReadBody(conn io.Reader, b interface{}) error {
|
2020-11-30 23:40:08 +03:00
|
|
|
switch m := b.(type) {
|
|
|
|
case nil:
|
|
|
|
return nil
|
|
|
|
case *codec.Frame:
|
|
|
|
buf, err := ioutil.ReadAll(conn)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2021-04-12 19:20:17 +03:00
|
|
|
} else if len(buf) == 0 {
|
|
|
|
return nil
|
2020-11-30 23:40:08 +03:00
|
|
|
}
|
|
|
|
m.Data = buf
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
buf, err := ioutil.ReadAll(conn)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2021-04-12 19:20:17 +03:00
|
|
|
} else if len(buf) == 0 {
|
2021-04-12 16:52:10 +03:00
|
|
|
// not needed but similar changes in all codecs
|
|
|
|
return nil
|
2020-11-30 23:40:08 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return yaml.Unmarshal(buf, b)
|
|
|
|
}
|
|
|
|
|
2020-12-21 00:02:24 +03:00
|
|
|
func (c *yamlCodec) Write(conn io.Writer, m *codec.Message, b interface{}) error {
|
2020-11-30 23:40:08 +03:00
|
|
|
switch m := b.(type) {
|
|
|
|
case nil:
|
|
|
|
return nil
|
|
|
|
case *codec.Frame:
|
|
|
|
_, err := conn.Write(m.Data)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
buf, err := yaml.Marshal(b)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = conn.Write(buf)
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *yamlCodec) String() string {
|
|
|
|
return "yaml"
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCodec() codec.Codec {
|
|
|
|
return &yamlCodec{}
|
|
|
|
}
|