2020-12-01 00:07:38 +03:00
|
|
|
// Package xml provides a xml codec
|
|
|
|
package xml
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/xml"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
|
|
|
|
"github.com/unistack-org/micro/v3/codec"
|
|
|
|
)
|
|
|
|
|
|
|
|
type xmlCodec struct{}
|
|
|
|
|
|
|
|
func (c *xmlCodec) Marshal(b interface{}) ([]byte, error) {
|
|
|
|
switch m := b.(type) {
|
|
|
|
case nil:
|
|
|
|
return nil, nil
|
|
|
|
case *codec.Frame:
|
|
|
|
return m.Data, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return xml.Marshal(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *xmlCodec) Unmarshal(b []byte, v interface{}) error {
|
2021-04-12 19:19:08 +03:00
|
|
|
if len(b) == 0 {
|
2020-12-01 00:07:38 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
switch m := v.(type) {
|
|
|
|
case nil:
|
|
|
|
return nil
|
|
|
|
case *codec.Frame:
|
|
|
|
m.Data = b
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return xml.Unmarshal(b, v)
|
|
|
|
}
|
|
|
|
|
2020-12-21 00:01:47 +03:00
|
|
|
func (c *xmlCodec) ReadHeader(conn io.Reader, m *codec.Message, t codec.MessageType) error {
|
2020-12-01 00:07:38 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-12-21 00:01:47 +03:00
|
|
|
func (c *xmlCodec) ReadBody(conn io.Reader, b interface{}) error {
|
2020-12-01 00:07:38 +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:19:08 +03:00
|
|
|
} else if len(buf) == 0 {
|
|
|
|
return nil
|
2020-12-01 00:07:38 +03:00
|
|
|
}
|
|
|
|
m.Data = buf
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-04-12 16:45:56 +03:00
|
|
|
err := xml.NewDecoder(conn).Decode(b)
|
|
|
|
if err == io.EOF {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return err
|
2020-12-01 00:07:38 +03:00
|
|
|
}
|
|
|
|
|
2020-12-21 00:01:47 +03:00
|
|
|
func (c *xmlCodec) Write(conn io.Writer, m *codec.Message, b interface{}) error {
|
2020-12-01 00:07:38 +03:00
|
|
|
switch m := b.(type) {
|
|
|
|
case nil:
|
|
|
|
return nil
|
|
|
|
case *codec.Frame:
|
|
|
|
_, err := conn.Write(m.Data)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return xml.NewEncoder(conn).Encode(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *xmlCodec) String() string {
|
|
|
|
return "xml"
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCodec() codec.Codec {
|
|
|
|
return &xmlCodec{}
|
|
|
|
}
|