RPC in Go

To build an RPC system, you need three basic elements: serialization protocol, network model, and threading model. The codec in Go’s RPC basically handles the serialization protocol.

Methods can only have two serializable parameters. The second parameter must be a pointer type. They return an error type. The methods must be public.

The standard library’s RPC uses Go’s specific gob encoding by default. This makes it hard to call Go RPC services from other languages. In the microservices era, each RPC service and its users may use different programming languages. Cross-language support is essential for internet-era RPC. Thanks to RPC’s framework design, Go’s RPC can easily support different languages.

Go’s RPC framework has two distinctive features. First, RPC data packing can use plugins for custom encoding and decoding. Second, RPC builds on the abstract io.ReadWriteCloser interface. We can put RPC on different communication protocols.

Based on different protocols: HTTP, TCP, or other protocols that implement the ServerCodec interface.

type ServerCodec interface {
        ReadRequestHeader(*Request) error
        ReadRequestBody(interface{}) error
        WriteResponse(*Response, interface{}) error

        // Close can be called multiple times and must be idempotent.
        Close() error
}

Cross-Language Support

You can use JSON encoding instead of native gob encoding for cross-language calls. Use rpc.ServeCodec instead of rpc.ServeConn.