github.com/annwntech/go-micro/v2@v2.9.5/codec/codec.go (about) 1 // Package codec is an interface for encoding messages 2 package codec 3 4 import ( 5 "errors" 6 "io" 7 ) 8 9 const ( 10 Error MessageType = iota 11 Request 12 Response 13 Event 14 ) 15 16 var ( 17 ErrInvalidMessage = errors.New("invalid message") 18 ) 19 20 type MessageType int 21 22 // Takes in a connection/buffer and returns a new Codec 23 type NewCodec func(io.ReadWriteCloser) Codec 24 25 // Codec encodes/decodes various types of messages used within go-micro. 26 // ReadHeader and ReadBody are called in pairs to read requests/responses 27 // from the connection. Close is called when finished with the 28 // connection. ReadBody may be called with a nil argument to force the 29 // body to be read and discarded. 30 type Codec interface { 31 Reader 32 Writer 33 Close() error 34 String() string 35 } 36 37 type Reader interface { 38 ReadHeader(*Message, MessageType) error 39 ReadBody(interface{}) error 40 } 41 42 type Writer interface { 43 Write(*Message, interface{}) error 44 } 45 46 // Marshaler is a simple encoding interface used for the broker/transport 47 // where headers are not supported by the underlying implementation. 48 type Marshaler interface { 49 Marshal(interface{}) ([]byte, error) 50 Unmarshal([]byte, interface{}) error 51 String() string 52 } 53 54 // Message represents detailed information about 55 // the communication, likely followed by the body. 56 // In the case of an error, body may be nil. 57 type Message struct { 58 Id string 59 Type MessageType 60 Target string 61 Method string 62 Endpoint string 63 Error string 64 65 // The values read from the socket 66 Header map[string]string 67 Body []byte 68 }