How to build RPC server in golang (step by step with examples)
20 May 2016Overview
Remote procedure call (RPC) is basically a form of inter-process communication. It is widely used in distributed computing.
In this blog post, We will build a simple RPC server step by step.
1. Define an interface and shared structs
For sake of simplicity, we will choose an interface with two methods: Multiply
and Divide
, which perform *
and /
operations respectively.
There will be only two shared structs called Args
and Quotient
that will be used to pass arguments from client to server and represent the output of Multiply
and Divide
respectively.
2. Write implementation for the interface
Now, we will write struct which implements two methods we mentioned above: Multiply
and Divide
.
3. Implement a RPC server
Two ways we can implement a RPC server in golang:
3.1 HTTP RPC
In this case server will be listening for incoming connection using HTTP protocol, and will switch to RPC protocol afterwards.
Benefit of this approach is, you can perform authentication of client easily, before allowing RPC, using any authentication method supported by HTTP.
Internally, server listens for HTTP CONNECT
method, and then uses http.Hijacker
to hijack the connection.
3.2 TCP RPC
In this case server will be listening for incoming connection directly, instead of relying on HTTP protocol.
4. Implement a RPC client
We need to implement RPC client, based on which way we chose to build our server.