trpc.group/trpc-go/trpc-go@v1.0.3/docs/developer_guide/develop_plugins/protocol.md (about) 1 English | [中文](protocol.zh_CN.md) 2 3 # How to develop a protocol type plugin 4 5 This guide will introduce how to develop a protocol type plugin that does not depend on a configuration file. 6 7 To develop a protocol type plugin, you need to implement at least the following two sub-functions: 8 9 - Implement `codec.Framer` and `codec.FramerBuilder` interfaces to read the complete business package from the connection 10 - Implement `codec.Codec` interface to parse the binary request body from the complete binary network data package and package the binary response body into a complete binary network data package 11 12 In addition, depending on the specific protocol, you may also need to implement `codec.Serializer` and `codec.Compressor` interfaces. 13 14 The following uses the implementation of the "rawstring" protocol in trpc-codec as an example to introduce the related development steps. More specific code can be found [here](https://github.com/trpc-ecosystem/go-codec/tree/main/rawstring). 15 16 The "rawstring" protocol is a simple communication protocol based on tcp, characterized by using the "\n" character as the delimiter for sending and receiving packets. 17 18 ## Implement `codec.Framer` and `codec.FramerBuilder` interfaces 19 20 ```go 21 type FramerBuilder struct{} 22 23 func (fd *FramerBuilder) New(reader io.Reader) transport.Framer { 24 return &framer{ 25 reader: reader, 26 } 27 } 28 29 type framer struct { 30 reader io.Reader 31 } 32 33 func (f *framer) ReadFrame() (msg []byte, err error) { 34 reader := bufio.NewReader(f.reader) 35 return reader.ReadBytes('\n') 36 } 37 ``` 38 39 Register the implemented FramerBuilder to the `transport` package 40 41 ```go 42 var DefaultFramerBuilder = &FramerBuilder{} 43 func init() { 44 transport.RegisterFramerBuilder("rawstring", DefaultFramerBuilder) 45 } 46 ``` 47 48 ## Implement `codec.Codec` interface 49 50 ### Implement server-side Codec 51 52 ```go 53 type serverCodec struct{} 54 55 func (sc *serverCodec) Decode(_ codec.Msg, req []byte) ([]byte, error) { 56 return req, nil 57 } 58 59 func (sc *serverCodec) Encode(_ codec.Msg, rsp []byte) ([]byte, error) { 60 return []byte(string(rsp) + "\n"), nil 61 } 62 ``` 63 64 ### Implement client-side Codec 65 66 ```go 67 type clientCodec struct{} 68 69 func (cc *clientCodec) Encode(_ codec.Msg, reqBody []byte) ([]byte, error) { 70 return []byte(string(reqBody) + "\n"), nil 71 } 72 73 func (cc *clientCodec) Decode(_ codec.Msg, rspBody []byte) ([]byte, error) { 74 return rspBody, nil 75 } 76 ``` 77 78 ### Register the implemented Codec to the `codec` package 79 80 ```go 81 func init() { 82 codec.Register("rawstring", &serverCodec{}, &clientCodec{}) 83 } 84 ``` 85 86 ## More examples 87 88 For more examples, you can refer to the [trpc-codec code repository](https://github.com/trpc-ecosystem/go-codec)