Documentation ¶
Overview ¶
Package codec defines the business communication protocol of packing and unpacking.
Index ¶
- Constants
- Variables
- func Compress(compressorType int, in []byte) ([]byte, error)
- func CopyMsg(dst, src Msg)
- func Decompress(compressorType int, in []byte) ([]byte, error)
- func GetReaderSize() int
- func IsSafeFramer(f interface{}) bool
- func Marshal(serializationType int, body interface{}) ([]byte, error)
- func NewReader(r io.Reader) io.Reader
- func NewReaderSize(r io.Reader, size int) io.Reader
- func PutBackMessage(sourceMsg Msg)
- func Register(name string, serverCodec Codec, clientCodec Codec)
- func RegisterCompressor(compressType int, s Compressor)
- func RegisterSerializer(serializationType int, s Serializer)
- func SetReaderSize(size int)
- func Unmarshal(serializationType int, in []byte, body interface{}) error
- type Body
- type BytesBodyIn
- type BytesBodyOut
- type Codec
- type CommonMeta
- type Compressor
- type ContextKey
- type FBSerialization
- type Framer
- type FramerBuilder
- type GzipCompress
- type JSONPBSerialization
- type JSONSerialization
- type MetaData
- type Msg
- func EnsureMessage(ctx context.Context) (context.Context, Msg)
- func Message(ctx context.Context) Msg
- func WithCloneContextAndMessage(ctx context.Context) (context.Context, Msg)
- func WithCloneMessage(ctx context.Context) (context.Context, Msg)
- func WithNewMessage(ctx context.Context) (context.Context, Msg)
- type NoopCompress
- type NoopSerialization
- type PBSerialization
- type RequestType
- type SafeFramer
- type Serializer
- type SnappyBlockCompressor
- type SnappyCompress
- type XMLSerialization
- type ZlibCompress
Constants ¶
const ( // SendAndRecv means send one request and receive one response. SendAndRecv = RequestType(trpcpb.TrpcCallType_TRPC_UNARY_CALL) // SendOnly means only send request, no response. SendOnly = RequestType(trpcpb.TrpcCallType_TRPC_ONEWAY_CALL) )
const ( CompressTypeNoop = iota CompressTypeGzip CompressTypeSnappy CompressTypeZlib CompressTypeStreamSnappy CompressTypeBlockSnappy )
CompressType is the mode of body compress or decompress.
const ( ContextKeyMessage = ContextKey("TRPC_MESSAGE") // ServiceSectionLength is the length of service section, // service name example: trpc.app.server.service ServiceSectionLength = 4 )
trpc context key data
const ( // SerializationTypePB is protobuf serialization code. SerializationTypePB = 0 // SerializationTypeJSON is json serialization code. SerializationTypeJSON = 2 // SerializationTypeFlatBuffer is flatbuffer serialization code. SerializationTypeFlatBuffer = 3 // SerializationTypeNoop is bytes empty serialization code. SerializationTypeNoop = 4 // SerializationTypeXML is xml serialization code (application/xml for http). SerializationTypeXML = 5 // SerializationTypeTextXML is xml serialization code (text/xml for http). SerializationTypeTextXML = 6 // SerializationTypeUnsupported is unsupported serialization code. SerializationTypeUnsupported = 128 // SerializationTypeForm is used to handle form request. SerializationTypeForm = 129 // SerializationTypeGet is used to handle http get request. SerializationTypeGet = 130 // SerializationTypeFormData is used to handle form data. SerializationTypeFormData = 131 )
SerializationType defines the code of different serializers, such as protobuf, json, http-get-query and http-get-restful.
- code 0-127 is used for common modes in all language versions of trpc.
- code 128-999 is used for modes in any language specific version of trpc.
- code 1000+ is used for customized occasions in which conflicts should be avoided.
const DefaultReaderSize = 4 * 1024
DefaultReaderSize is the default size of reader in bit.
Variables ¶
var JSONAPI = jsoniter.ConfigCompatibleWithStandardLibrary
JSONAPI is used by tRPC JSON serialization when the object does not conform to protobuf proto.Message interface.
Deprecated: This global variable is exportable due to backward comparability issue but should not be modified. If users want to change the default behavior of internal JSON serialization, please use register your customized serializer function like:
codec.RegisterSerializer(codec.SerializationTypeJSON, yourOwnJSONSerializer)
var Marshaler = protojson.MarshalOptions{EmitUnpopulated: true, UseProtoNames: true, UseEnumNumbers: true}
Marshaler is jsonpb marshal object, users can change its params.
var Unmarshaler = protojson.UnmarshalOptions{DiscardUnknown: false}
Unmarshaler is jsonpb unmarshal object, users can chang its params.
Functions ¶
func Compress ¶
Compress returns the compressed data, the data is compressed by a specific compressor.
func CopyMsg ¶
func CopyMsg(dst, src Msg)
CopyMsg copy src Msg to dst. All fields of src msg will be copied to dst msg.
func Decompress ¶
Decompress returns the decompressed data, the data is decompressed by a specific compressor.
func IsSafeFramer ¶
func IsSafeFramer(f interface{}) bool
IsSafeFramer returns if this framer is safe when concurrent read. The input parameter f should implement SafeFramer interface. If not , this method will return false.
func Marshal ¶
Marshal returns the serialized bytes from body. The specific serialization mode is defined by serializationType code, protobuf is default mode.
func NewReaderSize ¶
NewReaderSize returns a reader with read buffer. Size <= 0 means no buffer.
func PutBackMessage ¶
func PutBackMessage(sourceMsg Msg)
PutBackMessage return struct Message to sync pool, and reset all the members of Message to default
func Register ¶
Register defines the logic of register an codec by name. It will be called by init function defined by third package. If there is no server codec, the second param serverCodec can be nil.
func RegisterCompressor ¶
func RegisterCompressor(compressType int, s Compressor)
RegisterCompressor register a specific compressor, which will be called by init function defined in third package.
func RegisterSerializer ¶
func RegisterSerializer(serializationType int, s Serializer)
RegisterSerializer registers serializer, will be called by init function in third package.
func SetReaderSize ¶
func SetReaderSize(size int)
SetReaderSize sets the size of read buffer in bit.
Types ¶
type Body ¶
type Body struct {
Data []byte
}
Body is bytes pack layer, it is not need serialized and used in gateway service generally.
type BytesBodyIn ¶
BytesBodyIn is used to receive custom type body.
type BytesBodyOut ¶
BytesBodyOut is used to receive custom type body.
type Codec ¶
type Codec interface { // Encode pack the body into binary buffer. // client: Encode(msg, reqBody)(request-buffer, err) // server: Encode(msg, rspBody)(response-buffer, err) Encode(message Msg, body []byte) (buffer []byte, err error) // Decode unpack the body from binary buffer // server: Decode(msg, request-buffer)(reqBody, err) // client: Decode(msg, response-buffer)(rspBody, err) Decode(message Msg, buffer []byte) (body []byte, err error) }
Codec defines the interface of business communication protocol, which contains head and body. It only parses the body in binary, and then the business body struct will be handled by serializer. In common, the body's protocol is pb, json, etc. Specially, we can register our own serializer to handle other body type.
type CommonMeta ¶
type CommonMeta map[interface{}]interface{}
CommonMeta is common meta message.
func (CommonMeta) Clone ¶
func (c CommonMeta) Clone() CommonMeta
Clone returns a copied common meta message.
type Compressor ¶
type Compressor interface { Compress(in []byte) (out []byte, err error) Decompress(in []byte) (out []byte, err error) }
Compressor is body compress and decompress interface.
func GetCompressor ¶
func GetCompressor(compressType int) Compressor
GetCompressor returns a specific compressor by type.
type ContextKey ¶
type ContextKey string
ContextKey is trpc context key type, the specific value is judged by interface, the interface will both judge value and type. Defining a new type can avoid string value conflict.
type FBSerialization ¶
type FBSerialization struct{}
FBSerialization provides the flatbuffers serialization mode. Flatbuffers official url: https://google.github.io/flatbuffers
func (*FBSerialization) Marshal ¶
func (*FBSerialization) Marshal(body interface{}) ([]byte, error)
Marshal returns the serialized bytes, body should be a flatbuffers.Builder.
func (*FBSerialization) Unmarshal ¶
func (*FBSerialization) Unmarshal(in []byte, body interface{}) error
Unmarshal deserializes the in bytes into body param, body should implement flatbuffersInit interface.
type FramerBuilder ¶
FramerBuilder defines how to build a framer. In general, each connection build a framer.
type GzipCompress ¶
type GzipCompress struct {
// contains filtered or unexported fields
}
GzipCompress is gzip compressor.
func (*GzipCompress) Compress ¶
func (c *GzipCompress) Compress(in []byte) ([]byte, error)
Compress returns binary data compressed by gzip.
func (*GzipCompress) Decompress ¶
func (c *GzipCompress) Decompress(in []byte) ([]byte, error)
Decompress returns binary data decompressed by gzip.
type JSONPBSerialization ¶
type JSONPBSerialization struct{}
JSONPBSerialization provides jsonpb serialization mode. It is based on protobuf/jsonpb. This serializer will firstly try jsonpb's serialization. If object does not conform to protobuf proto.Message interface, json-iterator will be used.
func (*JSONPBSerialization) Marshal ¶
func (s *JSONPBSerialization) Marshal(body interface{}) ([]byte, error)
Marshal returns the serialized bytes in jsonpb protocol.
func (*JSONPBSerialization) Unmarshal ¶
func (s *JSONPBSerialization) Unmarshal(in []byte, body interface{}) error
Unmarshal deserialize the in bytes into body.
type JSONSerialization ¶
type JSONSerialization struct{}
JSONSerialization provides json serialization mode. golang official json package is implemented by reflection, and has very low performance. So trpc-go choose json-iterator package to implement json serialization.
func (*JSONSerialization) Marshal ¶
func (s *JSONSerialization) Marshal(body interface{}) ([]byte, error)
Marshal returns the serialized bytes in json protocol.
func (*JSONSerialization) Unmarshal ¶
func (s *JSONSerialization) Unmarshal(in []byte, body interface{}) error
Unmarshal deserializes the in bytes into body.
type Msg ¶
type Msg interface { // Context returns rpc context Context() context.Context // WithRemoteAddr sets upstream address for server, // or downstream address for client. WithRemoteAddr(addr net.Addr) // WithLocalAddr sets server local address. WithLocalAddr(addr net.Addr) // RemoteAddr returns upstream address for server, // or downstream address for client. RemoteAddr() net.Addr // LocalAddr returns server local address. LocalAddr() net.Addr // WithNamespace sets server namespace. WithNamespace(string) // Namespace returns server namespace. Namespace() string // WithEnvName sets server environment. WithEnvName(string) // EnvName returns server environment. EnvName() string // WithSetName sets server set name. WithSetName(string) // SetName returns server set name. SetName() string // WithEnvTransfer sets environment message for transfer. WithEnvTransfer(string) // EnvTransfer returns environment message for transfer. EnvTransfer() string // WithRequestTimeout sets the upstream timeout for server, // or downstream timeout for client. WithRequestTimeout(time.Duration) // RequestTimeout returns the upstream timeout for server, // or downstream timeout for client. RequestTimeout() time.Duration // WithSerializationType sets serialization type. WithSerializationType(int) // SerializationType returns serialization type. SerializationType() int // WithCompressType sets compress type. WithCompressType(int) // CompressType returns compress type. CompressType() int // WithServerRPCName sets server handler method name. WithServerRPCName(string) // WithClientRPCName sets client rpc name for downstream. WithClientRPCName(string) // ServerRPCName returns method name of current server handler name, // such as /trpc.app.server.service/method. ServerRPCName() string // ClientRPCName returns method name of downstream interface. ClientRPCName() string // WithCallerServiceName sets caller service name. WithCallerServiceName(string) // WithCalleeServiceName sets callee service name. WithCalleeServiceName(string) // WithCallerApp sets caller app. For server this app is upstream app, // but for client, is its own app. WithCallerApp(string) // WithCallerServer sets caller server. For server this server is upstream server, // but for client, is its own server. WithCallerServer(string) // WithCallerService sets caller service, For server this service is upstream service, // but for client, is its own service. WithCallerService(string) // WithCallerMethod sets caller method, For server this mothod is upstream mothod, // but for client, is its own method. WithCallerMethod(string) // WithCalleeApp sets callee app. For server, this app is its own app, // but for client, is downstream's app. WithCalleeApp(string) // WithCalleeServer sets callee server. For server, this server is its own server, // but for client, is downstream's server. WithCalleeServer(string) // WithCalleeService sets callee service. For server, this service is its own service, // but for client, is downstream's service. WithCalleeService(string) // WithCalleeMethod sets callee method. For server, this method is its own method, // but for client, is downstream's method. WithCalleeMethod(string) // CallerServiceName returns caller service name, such as trpc.app.server.service. // For server, this name is upstream's service name, but for client, is its own service name. CallerServiceName() string // CallerApp returns caller app. For server, this app is upstream's app, // but for client, is its own app. CallerApp() string // CallerServer returns caller server. For server, this is upstream's server, // but for client, is its own server. CallerServer() string // CallerService returns caller service. For server, this service is upstream's service, // but for client, is its own service. CallerService() string // CallerMethod returns caller method. For server, this method is upstream's method, // but for client, is its own method. CallerMethod() string // CalleeServiceName returns callee service name. For server, this name is its own service name, // but for client, is downstream's service name. CalleeServiceName() string // CalleeApp returns callee app. For server, this app is its own app, // but for client, is downstream's app. CalleeApp() string // CalleeServer returns callee server. For server, this server name is its own name, // but for client, is downstream's server name. CalleeServer() string // CalleeService returns callee service. For server, this service is its own service, // but for client, is downstream's service. CalleeService() string // CalleeMethod returns callee method. For server, this method is its own method, // but for client, is downstream's method. CalleeMethod() string // CalleeContainerName sets callee container name. CalleeContainerName() string // WithCalleeContainerName return callee container name. WithCalleeContainerName(string) // WithServerMetaData sets server meta data. WithServerMetaData(MetaData) // ServerMetaData returns server meta data. ServerMetaData() MetaData // WithFrameHead sets frame head. WithFrameHead(interface{}) // FrameHead returns frame head. FrameHead() interface{} // WithServerReqHead sets server request head. WithServerReqHead(interface{}) // ServerReqHead returns server request head. ServerReqHead() interface{} // WithServerRspHead sets server response head, this head will return to upstream. WithServerRspHead(interface{}) // ServerRspHead returns server response head, this head will return to upstream. ServerRspHead() interface{} // WithDyeing sets dyeing mark. WithDyeing(bool) // Dyeing returns dyeing mark. Dyeing() bool // WithDyeingKey sets dyeing key. WithDyeingKey(string) // DyeingKey returns dyeing key. DyeingKey() string // WithServerRspErr sets response error for server. WithServerRspErr(error) // ServerRspErr returns response error for server. ServerRspErr() *errs.Error // WithClientMetaData sets client meta data. WithClientMetaData(MetaData) // ClientMetaData returns client meta data. ClientMetaData() MetaData // WithClientReqHead sets client request head. WithClientReqHead(interface{}) // ClientReqHead returns client request head. ClientReqHead() interface{} // WithClientRspErr sets response error for client. WithClientRspErr(error) // ClientRspErr returns response error for client. ClientRspErr() error // WithClientRspHead sets response head for client. WithClientRspHead(interface{}) // ClientRspHead returns response head for client. ClientRspHead() interface{} // WithLogger sets logger into context. WithLogger(interface{}) // Logger returns logger from context. Logger() interface{} // WithRequestID sets request id. WithRequestID(uint32) // RequestID returns request id. RequestID() uint32 // WithStreamID sets stream id. WithStreamID(uint32) // StreamID return stream id. StreamID() uint32 // StreamFrame sets stream frame. StreamFrame() interface{} // WithStreamFrame returns stream frame. WithStreamFrame(interface{}) // WithCalleeSetName sets callee set name. WithCalleeSetName(string) // CalleeSetName returns callee set name. CalleeSetName() string // WithCommonMeta sets common meta data. WithCommonMeta(CommonMeta) // CommonMeta returns common meta data. CommonMeta() CommonMeta // WithCallType sets call type. WithCallType(RequestType) // CallType returns call type. CallType() RequestType }
Msg defines core message data for multi protocol, business protocol should set this message when packing and unpacking data.
func EnsureMessage ¶
EnsureMessage returns context and message, if there is a message in context, returns the original one, if not, returns a new one.
func WithCloneContextAndMessage ¶
WithCloneContextAndMessage creates a new context, then copy the message of current context into new context, this method will return the new context and message for stream mod.
func WithCloneMessage ¶
WithCloneMessage copy a new message and put into context, each rpc call should create a new message, this method will be called by client stub.
type NoopCompress ¶
type NoopCompress struct { }
NoopCompress is an empty compressor
func (*NoopCompress) Compress ¶
func (c *NoopCompress) Compress(in []byte) ([]byte, error)
Compress returns the origin data.
func (*NoopCompress) Decompress ¶
func (c *NoopCompress) Decompress(in []byte) ([]byte, error)
Decompress returns the origin data.
type NoopSerialization ¶
type NoopSerialization struct { }
NoopSerialization provides empty serialization, it is used to serialize bytes.
func (*NoopSerialization) Marshal ¶
func (s *NoopSerialization) Marshal(body interface{}) ([]byte, error)
Marshal returns the serialized bytes. body should be a Body or implements BytesBodyOut interface.
func (*NoopSerialization) Unmarshal ¶
func (s *NoopSerialization) Unmarshal(in []byte, body interface{}) error
Unmarshal deserializes the in bytes into body, body should be a Body or implements BytesBodyIn interface.
type PBSerialization ¶
type PBSerialization struct{}
PBSerialization provides protobuf serialization mode.
func (*PBSerialization) Marshal ¶
func (s *PBSerialization) Marshal(body interface{}) ([]byte, error)
Marshal returns the serialized bytes in protobuf protocol.
func (*PBSerialization) Unmarshal ¶
func (s *PBSerialization) Unmarshal(in []byte, body interface{}) error
Unmarshal deserializes the in bytes into body.
type RequestType ¶
type RequestType int
RequestType is the type of client request, such as SendAndRecv,SendOnly.
type SafeFramer ¶
type SafeFramer interface { Framer // IsSafe returns if this framer is safe when concurrent read. IsSafe() bool }
SafeFramer is a special framer, provides an isSafe() method to describe if it is safe when concurrent read.
type Serializer ¶
type Serializer interface { // Unmarshal deserialize the in bytes into body Unmarshal(in []byte, body interface{}) error // Marshal returns the bytes serialized from body. Marshal(body interface{}) (out []byte, err error) }
Serializer defines body serialization interface.
func GetSerializer ¶
func GetSerializer(serializationType int) Serializer
GetSerializer returns the serializer defined by serialization code.
type SnappyBlockCompressor ¶
type SnappyBlockCompressor struct{}
SnappyBlockCompressor is snappy compressor using snappy block format.
func NewSnappyBlockCompressor ¶
func NewSnappyBlockCompressor() *SnappyBlockCompressor
NewSnappyBlockCompressor returns a block format snappy compressor instance.
func (*SnappyBlockCompressor) Compress ¶
func (c *SnappyBlockCompressor) Compress(in []byte) ([]byte, error)
Compress returns binary data compressed by snappy block formats.
func (*SnappyBlockCompressor) Decompress ¶
func (c *SnappyBlockCompressor) Decompress(in []byte) ([]byte, error)
Decompress returns binary data decompressed by snappy block formats.
type SnappyCompress ¶
type SnappyCompress struct {
// contains filtered or unexported fields
}
SnappyCompress is snappy compressor using stream snappy format.
There are actually two Snappy formats: block and stream. They are related, but different: trying to decompress block-compressed data as a Snappy stream will fail, and vice versa.
func NewSnappyCompressor ¶
func NewSnappyCompressor() *SnappyCompress
NewSnappyCompressor returns a stream format snappy compressor instance.
func (*SnappyCompress) Compress ¶
func (c *SnappyCompress) Compress(in []byte) ([]byte, error)
Compress returns binary data compressed by snappy stream format.
func (*SnappyCompress) Decompress ¶
func (c *SnappyCompress) Decompress(in []byte) ([]byte, error)
Decompress returns binary data decompressed by snappy stream format.
type XMLSerialization ¶
type XMLSerialization struct{}
XMLSerialization provides xml serialization mode.
func (*XMLSerialization) Marshal ¶
func (*XMLSerialization) Marshal(body interface{}) ([]byte, error)
Marshal returns the serialized bytes in xml protocol.
func (*XMLSerialization) Unmarshal ¶
func (*XMLSerialization) Unmarshal(in []byte, body interface{}) error
Unmarshal deserializes the in bytes into body.
type ZlibCompress ¶
type ZlibCompress struct { }
ZlibCompress is zlib compressor.
func (*ZlibCompress) Compress ¶
func (c *ZlibCompress) Compress(in []byte) ([]byte, error)
Compress returns binary data compressed by zlib.
func (*ZlibCompress) Decompress ¶
func (c *ZlibCompress) Decompress(in []byte) ([]byte, error)
Decompress returns binary data decompressed by zlib.