1
0
mirror of https://github.com/go-micro/go-micro.git synced 2025-01-17 17:44:30 +02:00
go-micro/codec/text/text.go

78 lines
1.2 KiB
Go
Raw Normal View History

2019-05-31 00:38:05 +01:00
// Package text reads any text/* content-type
package text
import (
"fmt"
"io"
2024-06-04 21:40:43 +01:00
"go-micro.dev/v5/codec"
2019-05-31 00:38:05 +01:00
)
type Codec struct {
Conn io.ReadWriteCloser
}
2022-09-30 16:27:07 +02:00
// Frame gives us the ability to define raw data to send over the pipes.
2019-05-31 00:38:05 +01:00
type Frame struct {
Data []byte
}
func (c *Codec) ReadHeader(m *codec.Message, t codec.MessageType) error {
return nil
}
func (c *Codec) ReadBody(b interface{}) error {
// read bytes
buf, err := io.ReadAll(c.Conn)
2019-05-31 00:38:05 +01:00
if err != nil {
return err
}
2019-12-03 15:25:58 +08:00
switch v := b.(type) {
2019-06-10 12:42:43 +01:00
case *string:
*v = string(buf)
2019-05-31 00:38:05 +01:00
case *[]byte:
*v = buf
case *Frame:
v.Data = buf
default:
return fmt.Errorf("failed to read body: %v is not type of *[]byte", b)
}
return nil
}
func (c *Codec) Write(m *codec.Message, b interface{}) error {
var v []byte
2019-12-03 15:25:58 +08:00
switch ve := b.(type) {
2019-05-31 00:38:05 +01:00
case *Frame:
2019-12-03 15:25:58 +08:00
v = ve.Data
2019-05-31 00:38:05 +01:00
case *[]byte:
v = *ve
2019-06-10 12:42:43 +01:00
case *string:
v = []byte(*ve)
case string:
v = []byte(ve)
2019-05-31 00:38:05 +01:00
case []byte:
2019-12-03 15:25:58 +08:00
v = ve
2019-05-31 00:38:05 +01:00
default:
return fmt.Errorf("failed to write: %v is not type of *[]byte or []byte", b)
}
_, err := c.Conn.Write(v)
return err
}
func (c *Codec) Close() error {
return c.Conn.Close()
}
func (c *Codec) String() string {
2019-06-10 12:42:43 +01:00
return "text"
2019-05-31 00:38:05 +01:00
}
func NewCodec(c io.ReadWriteCloser) codec.Codec {
return &Codec{
Conn: c,
}
}