github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/codec/codec.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); 2 // you may not use this file except in compliance with the License. 3 // You may obtain a copy of the License at 4 // 5 // https://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, 9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 // See the License for the specific language governing permissions and 11 // limitations under the License. 12 // 13 // Original source: github.com/micro/go-micro/v3/codec/codec.go 14 15 // Package codec is an interface for encoding messages 16 package codec 17 18 import ( 19 "errors" 20 "io" 21 ) 22 23 const ( 24 Error MessageType = iota 25 Request 26 Response 27 Event 28 ) 29 30 var ( 31 ErrInvalidMessage = errors.New("invalid message") 32 ) 33 34 type MessageType int 35 36 // Takes in a connection/buffer and returns a new Codec 37 type NewCodec func(io.ReadWriteCloser) Codec 38 39 // Codec encodes/decodes various types of messages used within go-micro. 40 // ReadHeader and ReadBody are called in pairs to read requests/responses 41 // from the connection. Close is called when finished with the 42 // connection. ReadBody may be called with a nil argument to force the 43 // body to be read and discarded. 44 type Codec interface { 45 Reader 46 Writer 47 Close() error 48 String() string 49 } 50 51 type Reader interface { 52 ReadHeader(*Message, MessageType) error 53 ReadBody(interface{}) error 54 } 55 56 type Writer interface { 57 Write(*Message, interface{}) error 58 } 59 60 // Marshaler is a simple encoding interface used for the broker/transport 61 // where headers are not supported by the underlying implementation. 62 type Marshaler interface { 63 Marshal(interface{}) ([]byte, error) 64 Unmarshal([]byte, interface{}) error 65 String() string 66 } 67 68 // Message represents detailed information about 69 // the communication, likely followed by the body. 70 // In the case of an error, body may be nil. 71 type Message struct { 72 Id string 73 Type MessageType 74 Target string 75 Method string 76 Endpoint string 77 Error string 78 79 // The values read from the socket 80 Header map[string]string 81 Body []byte 82 }