trpc.group/trpc-go/trpc-go@v1.0.3/codec/codec.go (about) 1 // 2 // 3 // Tencent is pleased to support the open source community by making tRPC available. 4 // 5 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 6 // All rights reserved. 7 // 8 // If you have downloaded a copy of the tRPC source code from Tencent, 9 // please note that tRPC source code is licensed under the Apache 2.0 License, 10 // A copy of the Apache 2.0 License is included in this file. 11 // 12 // 13 14 // Package codec defines the business communication protocol of 15 // packing and unpacking. 16 package codec 17 18 import ( 19 "sync" 20 21 trpcpb "trpc.group/trpc/trpc-protocol/pb/go/trpc" 22 ) 23 24 // RequestType is the type of client request, such as SendAndRecv,SendOnly. 25 type RequestType int 26 27 const ( 28 // SendAndRecv means send one request and receive one response. 29 SendAndRecv = RequestType(trpcpb.TrpcCallType_TRPC_UNARY_CALL) 30 // SendOnly means only send request, no response. 31 SendOnly = RequestType(trpcpb.TrpcCallType_TRPC_ONEWAY_CALL) 32 ) 33 34 // Codec defines the interface of business communication protocol, 35 // which contains head and body. It only parses the body in binary, 36 // and then the business body struct will be handled by serializer. 37 // In common, the body's protocol is pb, json, etc. Specially, 38 // we can register our own serializer to handle other body type. 39 type Codec interface { 40 // Encode pack the body into binary buffer. 41 // client: Encode(msg, reqBody)(request-buffer, err) 42 // server: Encode(msg, rspBody)(response-buffer, err) 43 Encode(message Msg, body []byte) (buffer []byte, err error) 44 45 // Decode unpack the body from binary buffer 46 // server: Decode(msg, request-buffer)(reqBody, err) 47 // client: Decode(msg, response-buffer)(rspBody, err) 48 Decode(message Msg, buffer []byte) (body []byte, err error) 49 } 50 51 var ( 52 clientCodecs = make(map[string]Codec) 53 serverCodecs = make(map[string]Codec) 54 lock sync.RWMutex 55 ) 56 57 // Register defines the logic of register an codec by name. It will be 58 // called by init function defined by third package. If there is no server codec, 59 // the second param serverCodec can be nil. 60 func Register(name string, serverCodec Codec, clientCodec Codec) { 61 lock.Lock() 62 serverCodecs[name] = serverCodec 63 clientCodecs[name] = clientCodec 64 lock.Unlock() 65 } 66 67 // GetServer returns the server codec by name. 68 func GetServer(name string) Codec { 69 lock.RLock() 70 c := serverCodecs[name] 71 lock.RUnlock() 72 return c 73 } 74 75 // GetClient returns the client codec by name. 76 func GetClient(name string) Codec { 77 lock.RLock() 78 c := clientCodecs[name] 79 lock.RUnlock() 80 return c 81 }