gRPC Basics - Go

This tutorial provides a basic Go programmer’s introduction toworking with gRPC.

By walking through this example you’ll learn how to:

  • Define a service in a .proto file.
  • Generate server and client code using the protocol buffer compiler.
  • Use the Go gRPC API to write a simple client and server for your service.

It assumes that you have read theOverview and are familiar withprotocol buffers.Note that the example in this tutorial uses the proto3 version of the protocolbuffers language: you can find out more in theproto3 languageguide and theGo generated codeguide.

Why use gRPC?

Our example is a simple route mapping application that lets clients getinformation about features on their route, create a summary of their route, andexchange route information such as traffic updates with the server and otherclients.

With gRPC we can define our service once in a .proto file and implement clientsand servers in any of gRPC’s supported languages, which in turn can be run inenvironments ranging from servers inside Google to your own tablet - all thecomplexity of communication between different languages and environments ishandled for you by gRPC. We also get all the advantages of working with protocolbuffers, including efficient serialization, a simple IDL, and easy interfaceupdating.

Example code and setup

The example code for our tutorial is ingrpc/grpc-go/examples/route_guide.To download the example, clone the grpc-go repository by running the followingcommand:

  1. $ go get google.golang.org/grpc

Then change your current directory to grpc-go/examples/route_guide:

  1. $ cd $GOPATH/src/google.golang.org/grpc/examples/route_guide

You also should have the relevant tools installed to generate the server andclient interface code - if you don’t already, follow the setup instructions inthe Go quick start guide.

Defining the service

Our first step (as you’ll know from theOverview) is todefine the gRPC service and the method request and response types usingprotocol buffers.You can see the complete .proto file inexamples/route_guide/routeguide/route_guide.proto.

To define a service, you specify a named service in your .proto file:

  1. service RouteGuide {
  2. ...
  3. }

Then you define rpc methods inside your service definition, specifying theirrequest and response types. gRPC lets you define four kinds of service method,all of which are used in the RouteGuide service:

  • A simple RPC where the client sends a request to the server using the stuband waits for a response to come back, just like a normal function call.
  1. // Obtains the feature at a given position.
  2. rpc GetFeature(Point) returns (Feature) {}
  • A server-side streaming RPC where the client sends a request to the serverand gets a stream to read a sequence of messages back. The client reads fromthe returned stream until there are no more messages. As you can see in ourexample, you specify a server-side streaming method by placing the streamkeyword before the response type.
  1. // Obtains the Features available within the given Rectangle. Results are
  2. // streamed rather than returned at once (e.g. in a response message with a
  3. // repeated field), as the rectangle may cover a large area and contain a
  4. // huge number of features.
  5. rpc ListFeatures(Rectangle) returns (stream Feature) {}
  • A client-side streaming RPC where the client writes a sequence of messagesand sends them to the server, again using a provided stream. Once the clienthas finished writing the messages, it waits for the server to read them alland return its response. You specify a client-side streaming method by placingthe stream keyword before the request type.
  1. // Accepts a stream of Points on a route being traversed, returning a
  2. // RouteSummary when traversal is completed.
  3. rpc RecordRoute(stream Point) returns (RouteSummary) {}
  • A bidirectional streaming RPC where both sides send a sequence of messagesusing a read-write stream. The two streams operate independently, so clientsand servers can read and write in whatever order they like: for example, theserver could wait to receive all the client messages before writing itsresponses, or it could alternately read a message then write a message, orsome other combination of reads and writes. The order of messages in eachstream is preserved. You specify this type of method by placing the streamkeyword before both the request and the response.
  1. // Accepts a stream of RouteNotes sent while a route is being traversed,
  2. // while receiving other RouteNotes (e.g. from other users).
  3. rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}

Our .proto file also contains protocol buffer message type definitions for allthe request and response types used in our service methods - for example, here’sthe Point message type:

  1. // Points are represented as latitude-longitude pairs in the E7 representation
  2. // (degrees multiplied by 10**7 and rounded to the nearest integer).
  3. // Latitudes should be in the range +/- 90 degrees and longitude should be in
  4. // the range +/- 180 degrees (inclusive).
  5. message Point {
  6. int32 latitude = 1;
  7. int32 longitude = 2;
  8. }

Generating client and server code

Next we need to generate the gRPC client and server interfaces from our .protoservice definition. We do this using the protocol buffer compiler protoc witha special gRPC Go plugin.This is similar to what we did in thequickstart guide.

From the route_guide example directory, run:

  1. protoc -I routeguide/ routeguide/route_guide.proto --go_out=plugins=grpc:routeguide

Running this command generates the following file in the routeguide directoryunder the route_guide example directory:

  • route_guide.pb.go

This contains:

  • All the protocol buffer code to populate, serialize, and retrieve our requestand response message types
  • An interface type (or stub) for clients to call with the methods defined inthe RouteGuide service.
  • An interface type for servers to implement, also with the methods defined inthe RouteGuide service.

Creating the server

First let’s look at how we create a RouteGuide server. If you’re onlyinterested in creating gRPC clients, you can skip this section and go straighttoCreating the client (though you might find it interestinganyway!).

There are two parts to making our RouteGuide service do its job:

  • Implementing the service interface generated from our service definition:doing the actual “work” of our service.
  • Running a gRPC server to listen for requests from clients and dispatch them tothe right service implementation.

You can find our example RouteGuide server ingrpc-go/examples/route_guide/server/server.go.Let’s take a closer look at how it works.

Implementing RouteGuide

As you can see, our server has a routeGuideServer struct type that implementsthe generated RouteGuideServer interface:

  1. type routeGuideServer struct {
  2. ...
  3. }
  4. ...
  5. func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
  6. ...
  7. }
  8. ...
  9. func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
  10. ...
  11. }
  12. ...
  13. func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error {
  14. ...
  15. }
  16. ...
  17. func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
  18. ...
  19. }
  20. ...

Simple RPC

routeGuideServer implements all our service methods. Let’s look at thesimplest type first, GetFeature, which just gets a Point from the client andreturns the corresponding feature information from its database in a Feature.

  1. func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
  2. for _, feature := range s.savedFeatures {
  3. if proto.Equal(feature.Location, point) {
  4. return feature, nil
  5. }
  6. }
  7. // No feature was found, return an unnamed feature
  8. return &pb.Feature{"", point}, nil
  9. }

The method is passed a context object for the RPC and the client’s Pointprotocol buffer request. It returns a Feature protocol buffer object with theresponse information and an error. In the method we populate the Featurewith the appropriate information, and then return it along with an nil errorto tell gRPC that we’ve finished dealing with the RPC and that the Feature canbe returned to the client.

Server-side streaming RPC

Now let’s look at one of our streaming RPCs. ListFeatures is a server-sidestreaming RPC, so we need to send back multiple Features to our client.

  1. func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
  2. for _, feature := range s.savedFeatures {
  3. if inRange(feature.Location, rect) {
  4. if err := stream.Send(feature); err != nil {
  5. return err
  6. }
  7. }
  8. }
  9. return nil
  10. }

As you can see, instead of getting simple request and response objects in ourmethod parameters, this time we get a request object (the Rectangle in whichour client wants to find Features) and a specialRouteGuide_ListFeaturesServer object to write our responses.

In the method, we populate as many Feature objects as we need to return,writing them to the RouteGuide_ListFeaturesServer using its Send() method.Finally, as in our simple RPC, we return a nil error to tell gRPC that we’vefinished writing responses. Should any error happen in this call, we return anon-nil error; the gRPC layer will translate it into an appropriate RPC statusto be sent on the wire.

Client-side streaming RPC

Now let’s look at something a little more complicated: the client-side streamingmethod RecordRoute, where we get a stream of Points from the client andreturn a single RouteSummary with information about their trip. As you cansee, this time the method doesn’t have a request parameter at all. Instead, itgets a RouteGuideRecordRouteServer stream, which the server can use to bothread _and write messages - it can receive client messages using its Recv()method and return its single response using its SendAndClose() method.

  1. func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error {
  2. var pointCount, featureCount, distance int32
  3. var lastPoint *pb.Point
  4. startTime := time.Now()
  5. for {
  6. point, err := stream.Recv()
  7. if err == io.EOF {
  8. endTime := time.Now()
  9. return stream.SendAndClose(&pb.RouteSummary{
  10. PointCount: pointCount,
  11. FeatureCount: featureCount,
  12. Distance: distance,
  13. ElapsedTime: int32(endTime.Sub(startTime).Seconds()),
  14. })
  15. }
  16. if err != nil {
  17. return err
  18. }
  19. pointCount++
  20. for _, feature := range s.savedFeatures {
  21. if proto.Equal(feature.Location, point) {
  22. featureCount++
  23. }
  24. }
  25. if lastPoint != nil {
  26. distance += calcDistance(lastPoint, point)
  27. }
  28. lastPoint = point
  29. }
  30. }

In the method body we use the RouteGuide_RecordRouteServer's Recv() methodto repeatedly read in our client’s requests to a request object (in this case aPoint) until there are no more messages: the server needs to check the errorreturned from Read() after each call. If this is nil, the stream is stillgood and it can continue reading; if it’s io.EOF the message stream has endedand the server can return its RouteSummary. If it has any other value, wereturn the error “as is” so that it’ll be translated to an RPC status by thegRPC layer.

Bidirectional streaming RPC

Finally, let’s look at our bidirectional streaming RPC RouteChat().

  1. func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
  2. for {
  3. in, err := stream.Recv()
  4. if err == io.EOF {
  5. return nil
  6. }
  7. if err != nil {
  8. return err
  9. }
  10. key := serialize(in.Location)
  11. ... // look for notes to be sent to client
  12. for _, note := range s.routeNotes[key] {
  13. if err := stream.Send(note); err != nil {
  14. return err
  15. }
  16. }
  17. }
  18. }

This time we get a RouteGuideRouteChatServer stream that, as in ourclient-side streaming example, can be used to read and write messages. However,this time we return values via our method’s stream while the client is stillwriting messages to _their message stream.

The syntax for reading and writing here is very similar to our client-streamingmethod, except the server uses the stream’s Send() method rather thanSendAndClose() because it’s writing multiple responses. Although each sidewill always get the other’s messages in the order they were written, both theclient and server can read and write in any order — the streams operatecompletely independently.

Starting the server

Once we’ve implemented all our methods, we also need to start up a gRPC serverso that clients can actually use our service. The following snippet shows how wedo this for our RouteGuide service:

  1. flag.Parse()
  2. lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
  3. if err != nil {
  4. log.Fatalf("failed to listen: %v", err)
  5. }
  6. grpcServer := grpc.NewServer()
  7. pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{})
  8. ... // determine whether to use TLS
  9. grpcServer.Serve(lis)

To build and start a server, we:

  • Specify the port we want to use to listen for client requests using lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port)).
  • Create an instance of the gRPC server using grpc.NewServer().
  • Register our service implementation with the gRPC server.
  • Call Serve() on the server with our port details to do a blocking waituntil the process is killed or Stop() is called.

Creating the client

In this section, we’ll look at creating a Go client for our RouteGuideservice. You can see our complete example client code ingrpc-go/examples/route_guide/client/client.go.

Creating a stub

To call service methods, we first need to create a gRPC channel to communicatewith the server. We create this by passing the server address and port number togrpc.Dial() as follows:

  1. conn, err := grpc.Dial(*serverAddr)
  2. if err != nil {
  3. ...
  4. }
  5. defer conn.Close()

You can use DialOptions to set the auth credentials (e.g., TLS, GCEcredentials, JWT credentials) in grpc.Dial if the service you request requiresthat - however, we don’t need to do this for our RouteGuide service.

Once the gRPC channel is setup, we need a client stub to perform RPCs. Weget this using the NewRouteGuideClient method provided in the pb package wegenerated from our .proto.

  1. client := pb.NewRouteGuideClient(conn)

Calling service methods

Now let’s look at how we call our service methods. Note that in gRPC-Go, RPCsoperate in a blocking/synchronous mode, which means that the RPC call waits forthe server to respond, and will either return a response or an error.

Simple RPC

Calling the simple RPC GetFeature is nearly as straightforward as calling alocal method.

  1. feature, err := client.GetFeature(context.Background(), &pb.Point{409146138, -746188906})
  2. if err != nil {
  3. ...
  4. }

As you can see, we call the method on the stub we got earlier. In our methodparameters we create and populate a request protocol buffer object (in our casePoint). We also pass a context.Context object which lets us change our RPC’sbehaviour if necessary, such as time-out/cancel an RPC in flight. If the calldoesn’t return an error, then we can read the response information from theserver from the first return value.

  1. log.Println(feature)

Server-side streaming RPC

Here’s where we call the server-side streaming method ListFeatures, whichreturns a stream of geographical Features. If you’ve already readCreatingthe server some of this may look very familiar - streaming RPCs areimplemented in a similar way on both sides.

  1. rect := &pb.Rectangle{ ... } // initialize a pb.Rectangle
  2. stream, err := client.ListFeatures(context.Background(), rect)
  3. if err != nil {
  4. ...
  5. }
  6. for {
  7. feature, err := stream.Recv()
  8. if err == io.EOF {
  9. break
  10. }
  11. if err != nil {
  12. log.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
  13. }
  14. log.Println(feature)
  15. }

As in the simple RPC, we pass the method a context and a request. However,instead of getting a response object back, we get back an instance ofRouteGuide_ListFeaturesClient. The client can use theRouteGuide_ListFeaturesClient stream to read the server’s responses.

We use the RouteGuide_ListFeaturesClient's Recv() method to repeatedly readin the server’s responses to a response protocol buffer object (in this case aFeature) until there are no more messages: the client needs to check the errorerr returned from Recv() after each call. If nil, the stream is still goodand it can continue reading; if it’s io.EOF then the message stream has ended;otherwise there must be an RPC error, which is passed over through err.

Client-side streaming RPC

The client-side streaming method RecordRoute is similar to the server-sidemethod, except that we only pass the method a context and get aRouteGuide_RecordRouteClient stream back, which we can use to both write _and_read messages.

  1. // Create a random number of random points
  2. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  3. pointCount := int(r.Int31n(100)) + 2 // Traverse at least two points
  4. var points []*pb.Point
  5. for i := 0; i < pointCount; i++ {
  6. points = append(points, randomPoint(r))
  7. }
  8. log.Printf("Traversing %d points.", len(points))
  9. stream, err := client.RecordRoute(context.Background())
  10. if err != nil {
  11. log.Fatalf("%v.RecordRoute(_) = _, %v", client, err)
  12. }
  13. for _, point := range points {
  14. if err := stream.Send(point); err != nil {
  15. if err == io.EOF {
  16. break
  17. }
  18. log.Fatalf("%v.Send(%v) = %v", stream, point, err)
  19. }
  20. }
  21. reply, err := stream.CloseAndRecv()
  22. if err != nil {
  23. log.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil)
  24. }
  25. log.Printf("Route summary: %v", reply)

The RouteGuide_RecordRouteClient has a Send() method that we can use to sendrequests to the server. Once we’ve finished writing our client’s requests to thestream using Send(), we need to call CloseAndRecv() on the stream to letgRPC know that we’ve finished writing and are expecting to receive a response.We get our RPC status from the err returned from CloseAndRecv(). If thestatus is nil, then the first return value from CloseAndRecv() will be avalid server response.

Bidirectional streaming RPC

Finally, let’s look at our bidirectional streaming RPC RouteChat(). As in thecase of RecordRoute, we only pass the method a context object and get back astream that we can use to both write and read messages. However, this time wereturn values via our method’s stream while the server is still writing messagesto their message stream.

  1. stream, err := client.RouteChat(context.Background())
  2. waitc := make(chan struct{})
  3. go func() {
  4. for {
  5. in, err := stream.Recv()
  6. if err == io.EOF {
  7. // read done.
  8. close(waitc)
  9. return
  10. }
  11. if err != nil {
  12. log.Fatalf("Failed to receive a note : %v", err)
  13. }
  14. log.Printf("Got message %s at point(%d, %d)", in.Message, in.Location.Latitude, in.Location.Longitude)
  15. }
  16. }()
  17. for _, note := range notes {
  18. if err := stream.Send(note); err != nil {
  19. log.Fatalf("Failed to send a note: %v", err)
  20. }
  21. }
  22. stream.CloseSend()
  23. <-waitc

The syntax for reading and writing here is very similar to our client-sidestreaming method, except we use the stream’s CloseSend() method once we’vefinished our call. Although each side will always get the other’s messages inthe order they were written, both the client and server can read and write inany order — the streams operate completely independently.

Try it out!

Work from the example directory:

  1. $ cd $GOPATH/src/google.golang.org/grpc/examples/route_guide

Run the server:

  1. $ go run server/server.go

From a different terminal, run the client:

  1. $ go run client/client.go