micro/codec/codec.go

70 lines
1.8 KiB
Go
Raw Normal View History

2016-12-14 15:41:48 +00:00
// Package codec is an interface for encoding messages
2015-11-27 00:17:36 +00:00
package codec
import (
"errors"
"io"
"github.com/unistack-org/micro/v3/metadata"
)
// Message types
const (
Error MessageType = iota
Request
Response
2019-07-07 12:44:09 +01:00
Event
)
var (
// ErrInvalidMessage returned when invalid messge passed to codec
ErrInvalidMessage = errors.New("invalid message")
// ErrUnknownContentType returned when content-type is unknown
ErrUnknownContentType = errors.New("unknown content-type")
)
var (
// DefaultMaxMsgSize specifies how much data codec can handle
DefaultMaxMsgSize int = 1024 * 1024 * 4 // 4Mb
// DefaultCodec is the global default codec
DefaultCodec Codec = NewCodec()
// DefaultTagName specifies struct tag name to control codec Marshal/Unmarshal
DefaultTagName = "codec"
)
// MessageType specifies message type for codec
type MessageType int
// Codec encodes/decodes various types of messages used within micro.
2015-12-02 01:38:56 +00:00
// ReadHeader and ReadBody are called in pairs to read requests/responses
// from the connection. Close is called when finished with the
// connection. ReadBody may be called with a nil argument to force the
// body to be read and discarded.
2015-11-27 00:17:36 +00:00
type Codec interface {
ReadHeader(io.Reader, *Message, MessageType) error
ReadBody(io.Reader, interface{}) error
Write(io.Writer, *Message, interface{}) error
2019-01-10 09:42:02 +00:00
Marshal(interface{}) ([]byte, error)
Unmarshal([]byte, interface{}) error
String() string
}
// Message represents detailed information about
// the communication, likely followed by the body.
// In the case of an error, body may be nil.
type Message struct {
Header metadata.Metadata
2019-01-10 21:25:31 +00:00
Target string
2019-01-18 10:12:57 +00:00
Method string
2019-01-10 21:25:31 +00:00
Endpoint string
Error string
Id string
Body []byte
Type MessageType
}
// NewMessage creates new codec message
func NewMessage(t MessageType) *Message {
return &Message{Type: t, Header: metadata.New(0)}
}