Creating the server

Now we have the service that we can use to create an RPC server very easily. However, the type used has to respect some rules for its methods to make them available:

  • The method's type and method itself are both exported.
  • The method has two arguments, both exported.
  • The second argument is a pointer.
  • The method returns an error.

The method should look something like this: func (t *T) Method(in T1, out *T2) error.

The next step is create a wrapper for the ReadingList that satisfies these rules:

// ReadingService adapts ReadingList for RPC
type ReadingService struct {
ReadingList
}

// sets the success pointer value from error
func setSuccess(err error, b *bool) error {
*b = err == nil
return err
}

We can redefine the book, add and remove functions using Book, which is an exported type, and built-in types:

func (r *ReadingService) AddBook(b Book, success *bool) error {
return setSuccess(r.ReadingList.AddBook(b), success)
}

func (r *ReadingService) RemoveBook(isbn string, success *bool) error {
return setSuccess(r.ReadingList.RemoveBook(isbn), success)
}

For the progress, we have two inputs (isbn and pages), so we have to define a structure that contains both, since the input must be a single argument:

func (r *ReadingService) GetProgress(isbn string, pages *int) (err error) {
*pages, err = r.ReadingList.GetProgress(isbn)
return err
}

type Progress struct {
ISBN string
Pages int
}

func (r *ReadingService) SetProgress(p Progress, success *bool) error {
return setSuccess(r.ReadingList.SetProgress(p.ISBN, p.Pages), success)
}

func (r *ReadingService) AdvanceProgress(p Progress, success *bool) error {
return setSuccess(r.ReadingList.AdvanceProgress(p.ISBN, p.Pages), success)
}

The defined type can be registered and used in an RPC server, which will use rpc.HandleHTTP to register the HTTP handler for the incoming RPC messages:

if len(os.Args) != 2 {
log.Fatalln("Please specify an address.")
}
if err := rpc.Register(&common.ReadingService{}); err != nil {
log.Fatalln(err)
}
rpc.HandleHTTP()

l, err := net.Listen("tcp", os.Args[1])
if err != nil {
log.Fatalln(err)
}
log.Println("Server Started")
if err := http.Serve(l, nil); err != nil {
log.Fatal(err)
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.151.220