https://pkg.go.dev/net/rpc

methods used pkg-functions

For a function to be called remotely for RPC

  • should be method i.e., should have receiver as per Go
  • should be public (name starts with uppercase)
  • should have 2 args
    • 1st arg can be interpreted as request body
    • 2nd arg is pointer to response body struct, called as reply
  • return error type
    • when method reaches end return nil

Now we can call our struct/type which acts as receiver for these procedures/methods

Server

  • create obj from struct which can be called remotely

  • start listening :port (this step can be done afterwards)

  • server way

    • server obj need to be created
    • register struct obj with rpc server
    • in an infinite loop, continuously
      • accept connections from listener with Accept()
      • server connection with server obj
  • raw-dogging way

    • register struct obj with net/rpc
    • handle http and start serving
    // ignore err handling
     
    var obj = new(type)
    lis, err := net.Listen("tcp", ":port")
    defer lis.close()
     
    // server way
    svr := rpc.NewServer()
    svr.Register(obj)
    for {
    	conn, err := lis.Accept()
    	svr.ServeConn(conn)
    }
     
    // raw-dogging way
    rpc.Register(obj)
    rpc.HandleHTTP()
    http.Serve(lis, nil)
     
    // either way, rpc will be served on :port 

Client

  • we’ll have same types/structs as used in server
  • additional to those, reqBody and resp struct(s) should be created accordingly
  • response of function call will in resp
client, err := rpc.DialHTTP("tcp", ":port")
 
client.Call("Type.Method", reqBody, &resp)