Go RPC

Go’s RPC is so far unique to Go. It is different to the other RPC systems, so a Go client will only talk to a Go server. It uses the Gob serialisation system discussed in chapter X, which defines the data types which can be used.

RPC systems generally make some restrictions on the functions that can be called across the network. This is so that the RPC system can properly determine what are value arguments to be sent, what are reference arguments to receive answers, and how to signal errors.

In Go, the restriction is that

  • the function must be public (begin with a capital letter);
  • have exactly two arguments, the first is a pointer to value data to be received by the function from the client, and the second is a pointer to hold the answers to be returned to the client; and
  • have a return value of type error

For example, a valid function is

  1. F(&T1, &T2) error

The restriction on arguments means that you typically have to define a structure type. Go’s RPC uses the gob package for marshalling and unmarshalling data, so the argument types have to follow the rules of gob as discussed in an earlier chapter.

We shall follow the example given in the Go documentation, as this illustrates the important points. The server performs two operations which are trivial - they do not require the “grunt” of RPC, but are simple to understand. The two operations are to multiply two integers, and the second is to find the quotient and remainder after dividing the first by the second.

The two values to be manipulated are given in a structure:

  1. type Values struct {
  2. X, Y int
  3. }

The sum is just an int, while the quotient/remainder is another structure

  1. type Quotient struct {
  2. Quo, Rem int
  3. }

We will have two functions, multiply and divide to be callable on the RPC server. These functions will need to be registered with the RPC system. The function Register takes a single parameter, which is an interface. So we need a type with these two functions:

  1. type Arith int
  2. func (t *Arith) Multiply(args *Args, reply *int) error {
  3. *reply = args.A * args.B
  4. return nil
  5. }
  6. func (t *Arith) Divide(args *Args, quo *Quotient) error {
  7. if args.B == 0 {
  8. return error.String("divide by zero")
  9. }
  10. quo.Quo = args.A / args.B
  11. quo.Rem = args.A % args.B
  12. return nil
  13. }

The underlying type of Arith is given as int. That doesn’t matter - any type could have done.

An object of this type can now be registered using Register, and then its methods can be called by the RPC system.

HTTP RPC Server

Any RPC needs a transport mechanism to get messages across the network. Go can use HTTP or TCP. The advantage of the HTTP mechanism is that it can leverage off the HTTP suport library. You need to add an RPC handler to the HTTP layer which is done using HandleHTTP and then start an HTTP server. The complete code is

  1. /**
  2. * ArithServer
  3. */
  4. package main
  5. import (
  6. "fmt"
  7. "net/rpc"
  8. "errors"
  9. "net/http"
  10. )
  11. type Args struct {
  12. A, B int
  13. }
  14. type Quotient struct {
  15. Quo, Rem int
  16. }
  17. type Arith int
  18. func (t *Arith) Multiply(args *Args, reply *int) error {
  19. *reply = args.A * args.B
  20. return nil
  21. }
  22. func (t *Arith) Divide(args *Args, quo *Quotient) error {
  23. if args.B == 0 {
  24. return errors.New("divide by zero")
  25. }
  26. quo.Quo = args.A / args.B
  27. quo.Rem = args.A % args.B
  28. return nil
  29. }
  30. func main() {
  31. arith := new(Arith)
  32. rpc.Register(arith)
  33. rpc.HandleHTTP()
  34. err := http.ListenAndServe(":1234", nil)
  35. if err != nil {
  36. fmt.Println(err.Error())
  37. }
  38. }

HTTP RPC client

The client needs to set up an HTTP connection to the RPC server. It needs to prepare a structure with the values to be sent, and the address of a variable to store the results in. Then it can make a Call with arguments:

  • The name of the remote function to execute
  • The values to be sent
  • The address of a variable to store the result in

A client that calls both functions of the arithmetic server is

  1. /**
  2. * ArithClient
  3. */
  4. package main
  5. import (
  6. "net/rpc"
  7. "fmt"
  8. "log"
  9. "os"
  10. )
  11. type Args struct {
  12. A, B int
  13. }
  14. type Quotient struct {
  15. Quo, Rem int
  16. }
  17. func main() {
  18. if len(os.Args) != 2 {
  19. fmt.Println("Usage: ", os.Args[0], "server")
  20. os.Exit(1)
  21. }
  22. serverAddress := os.Args[1]
  23. client, err := rpc.DialHTTP("tcp", serverAddress+":1234")
  24. if err != nil {
  25. log.Fatal("dialing:", err)
  26. }
  27. // Synchronous call
  28. args := Args{17, 8}
  29. var reply int
  30. err = client.Call("Arith.Multiply", args, &reply)
  31. if err != nil {
  32. log.Fatal("arith error:", err)
  33. }
  34. fmt.Printf("Arith: %d*%d=%d\n", args.A, args.B, reply)
  35. var quot Quotient
  36. err = client.Call("Arith.Divide", args, &quot)
  37. if err != nil {
  38. log.Fatal("arith error:", err)
  39. }
  40. fmt.Printf("Arith: %d/%d=%d remainder %d\n", args.A, args.B, quot.Quo, quot.Rem)
  41. }

TCP RPC server

A version of the server that uses TCP sockets is

  1. /**
  2. * TCPArithServer
  3. */
  4. package main
  5. import (
  6. "fmt"
  7. "net/rpc"
  8. "errors"
  9. "net"
  10. "os"
  11. )
  12. type Args struct {
  13. A, B int
  14. }
  15. type Quotient struct {
  16. Quo, Rem int
  17. }
  18. type Arith int
  19. func (t *Arith) Multiply(args *Args, reply *int) error {
  20. *reply = args.A * args.B
  21. return nil
  22. }
  23. func (t *Arith) Divide(args *Args, quo *Quotient) error {
  24. if args.B == 0 {
  25. return errors.New("divide by zero")
  26. }
  27. quo.Quo = args.A / args.B
  28. quo.Rem = args.A % args.B
  29. return nil
  30. }
  31. func main() {
  32. arith := new(Arith)
  33. rpc.Register(arith)
  34. tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
  35. checkError(err)
  36. listener, err := net.ListenTCP("tcp", tcpAddr)
  37. checkError(err)
  38. /* This works:
  39. rpc.Accept(listener)
  40. */
  41. /* and so does this:
  42. */
  43. for {
  44. conn, err := listener.Accept()
  45. if err != nil {
  46. continue
  47. }
  48. rpc.ServeConn(conn)
  49. }
  50. }
  51. func checkError(err error) {
  52. if err != nil {
  53. fmt.Println("Fatal error ", err.Error())
  54. os.Exit(1)
  55. }
  56. }

Note that the call to Accept is blocking, and just handles client connections. If the server wishes to do other work as well, it should call this in a goroutine.

TCP RPC client

A client that uses the TCP server and calls both functions of the arithmetic server is

  1. /**
  2. * TCPArithClient
  3. */
  4. package main
  5. import (
  6. "net/rpc"
  7. "fmt"
  8. "log"
  9. "os"
  10. )
  11. type Args struct {
  12. A, B int
  13. }
  14. type Quotient struct {
  15. Quo, Rem int
  16. }
  17. func main() {
  18. if len(os.Args) != 2 {
  19. fmt.Println("Usage: ", os.Args[0], "server:port")
  20. os.Exit(1)
  21. }
  22. service := os.Args[1]
  23. client, err := rpc.Dial("tcp", service)
  24. if err != nil {
  25. log.Fatal("dialing:", err)
  26. }
  27. // Synchronous call
  28. args := Args{17, 8}
  29. var reply int
  30. err = client.Call("Arith.Multiply", args, &reply)
  31. if err != nil {
  32. log.Fatal("arith error:", err)
  33. }
  34. fmt.Printf("Arith: %d*%d=%d\n", args.A, args.B, reply)
  35. var quot Quotient
  36. err = client.Call("Arith.Divide", args, &quot)
  37. if err != nil {
  38. log.Fatal("arith error:", err)
  39. }
  40. fmt.Printf("Arith: %d/%d=%d remainder %d\n", args.A, args.B, quot.Quo, quot.Rem)
  41. }

Matching values

We note that the types of the value arguments are not the same on the client and server. In the server, we have used Values while in the client we used Args. That doesn’t matter, as we are following the rules of gob serialisation, and the names an types of the two structures’ fields match. Better programming practise would say that the names should be the same!

However, this does point out a possible trap in using Go RPC. If we change the structure in the client to be, say,

  1. type Values struct {
  2. C, B int
  3. }

then gob has no problems: on the server-side the unmarshalling will ignore the value of C given by the client, and use the default zero value for A.

Using Go RPC will require a rigid enforcement of the stability of field names and types by the programmer. We note that there is no version control mechanism to do this, and no mechanism in gob to signal any possible mismatches.