1#gRPC Basics: Go
2
3This tutorial provides a basic Go programmer's introduction to working with gRPC. By walking through this example you'll learn how to:
4
5- Define a service in a .proto file.
6- Generate server and client code using the protocol buffer compiler.
7- Use the Go gRPC API to write a simple client and server for your service.
8
9It assumes that you have read the [Getting started](https://github.com/grpc/grpc/tree/master/examples) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, which is currently in alpha release:you can find out more in the [proto3 language guide](https://developers.google.com/protocol-buffers/docs/proto3) and see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository.
10
11This isn't a comprehensive guide to using gRPC in Go: more reference documentation is coming soon.
12
13## Why use gRPC?
14
15Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients.
16
17With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating.
18
19## Example code and setup
20
21The example code for our tutorial is in [grpc/grpc-go/examples/route_guide](https://github.com/grpc/grpc-go/tree/master/examples/route_guide). To download the example, clone the `grpc-go` repository by running the following command:
22```shell
23$ go get google.golang.org/grpc
24```
25
26Then change your current directory to `grpc-go/examples/route_guide`:
27```shell
28$ cd $GOPATH/src/google.golang.org/grpc/examples/route_guide
29```
30
31You also should have the relevant tools installed to generate the server and client interface code - if you don't already, follow the setup instructions in [the Go quick start guide](examples/).
32
33
34## Defining the service
35
36Our first step (as you'll know from the [quick start](http://www.grpc.io/docs/#quick-start)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`examples/route_guide/proto/route_guide.proto`](examples/route_guide/proto/route_guide.proto).
37
38To define a service, you specify a named `service` in your .proto file:
39
40```proto
41service RouteGuide {
42   ...
43}
44```
45
46Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service:
47
48- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call.
49```proto
50   // Obtains the feature at a given position.
51   rpc GetFeature(Point) returns (Feature) {}
52```
53
54- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type.
55```proto
56  // Obtains the Features available within the given Rectangle.  Results are
57  // streamed rather than returned at once (e.g. in a response message with a
58  // repeated field), as the rectangle may cover a large area and contain a
59  // huge number of features.
60  rpc ListFeatures(Rectangle) returns (stream Feature) {}
61```
62
63- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a client-side streaming method by placing the `stream` keyword before the *request* type.
64```proto
65  // Accepts a stream of Points on a route being traversed, returning a
66  // RouteSummary when traversal is completed.
67  rpc RecordRoute(stream Point) returns (RouteSummary) {}
68```
69
70- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response.
71```proto
72  // Accepts a stream of RouteNotes sent while a route is being traversed,
73  // while receiving other RouteNotes (e.g. from other users).
74  rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
75```
76
77Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type:
78```proto
79// Points are represented as latitude-longitude pairs in the E7 representation
80// (degrees multiplied by 10**7 and rounded to the nearest integer).
81// Latitudes should be in the range +/- 90 degrees and longitude should be in
82// the range +/- 180 degrees (inclusive).
83message Point {
84  int32 latitude = 1;
85  int32 longitude = 2;
86}
87```
88
89
90## Generating client and server code
91
92Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC Go plugin.
93
94For simplicity, we've provided a [bash script](https://github.com/grpc/grpc-go/blob/master/codegen.sh) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this by yourself, make sure you've installed protoc and followed the gRPC-Go [installation instructions](https://github.com/grpc/grpc-go/blob/master/README.md) first):
95
96```shell
97$ codegen.sh route_guide.proto
98```
99
100which actually runs:
101
102```shell
103$ protoc --go_out=plugins=grpc:. route_guide.proto
104```
105
106Running this command generates the following file in your current directory:
107- `route_guide.pb.go`
108
109This contains:
110- All the protocol buffer code to populate, serialize, and retrieve our request and response message types
111- An interface type (or *stub*) for clients to call with the methods defined in the `RouteGuide` service.
112- An interface type for servers to implement, also with the methods defined in the `RouteGuide` service.
113
114
115<a name="server"></a>
116## Creating the server
117
118First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client) (though you might find it interesting anyway!).
119
120There are two parts to making our `RouteGuide` service do its job:
121- Implementing the service interface generated from our service definition: doing the actual "work" of our service.
122- Running a gRPC server to listen for requests from clients and dispatch them to the right service implementation.
123
124You can find our example `RouteGuide` server in [grpc-go/examples/route_guide/server/server.go](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/server/server.go). Let's take a closer look at how it works.
125
126### Implementing RouteGuide
127
128As you can see, our server has a `routeGuideServer` struct type that implements the generated `RouteGuideServer` interface:
129
130```go
131type routeGuideServer struct {
132        ...
133}
134...
135
136func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
137        ...
138}
139...
140
141func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
142        ...
143}
144...
145
146func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error {
147        ...
148}
149...
150
151func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
152        ...
153}
154...
155```
156
157#### Simple RPC
158`routeGuideServer` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`.
159
160```go
161func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
162	for _, feature := range s.savedFeatures {
163		if proto.Equal(feature.Location, point) {
164			return feature, nil
165		}
166	}
167	// No feature was found, return an unnamed feature
168	return &pb.Feature{"", point}, nil
169}
170```
171
172The method is passed a context object for the RPC and the client's `Point` protocol buffer request. It returns a `Feature` protocol buffer object with the response information and an `error`. In the method we populate the `Feature` with the appropriate information, and then `return` it along with an `nil` error to tell gRPC that we've finished dealing with the RPC and that the `Feature` can be returned to the client.
173
174#### Server-side streaming RPC
175Now let's look at one of our streaming RPCs. `ListFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client.
176
177```go
178func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
179	for _, feature := range s.savedFeatures {
180		if inRange(feature.Location, rect) {
181			if err := stream.Send(feature); err != nil {
182				return err
183			}
184		}
185	}
186	return nil
187}
188```
189
190As you can see, instead of getting simple request and response objects in our method parameters, this time we get a request object (the `Rectangle` in which our client wants to find `Feature`s) and a special `RouteGuide_ListFeaturesServer` object to write our responses.
191
192In 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've finished writing responses. Should any error happen in this call, we return a non-`nil` error; the gRPC layer will translate it into an appropriate RPC status to be sent on the wire.
193
194#### Client-side streaming RPC
195Now let's look at something a little more complicated: the client-side streaming method `RecordRoute`, where we get a stream of `Point`s from the client and return a single `RouteSummary` with information about their trip. As you can see, this time the method doesn't have a request parameter at all. Instead, it gets a `RouteGuide_RecordRouteServer` stream, which the server can use to both read *and* write messages - it can receive client messages using its `Recv()` method and return its single response using its `SendAndClose()` method.
196
197```go
198func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error {
199	var pointCount, featureCount, distance int32
200	var lastPoint *pb.Point
201	startTime := time.Now()
202	for {
203		point, err := stream.Recv()
204		if err == io.EOF {
205			endTime := time.Now()
206			return stream.SendAndClose(&pb.RouteSummary{
207				PointCount:   pointCount,
208				FeatureCount: featureCount,
209				Distance:     distance,
210				ElapsedTime:  int32(endTime.Sub(startTime).Seconds()),
211			})
212		}
213		if err != nil {
214			return err
215		}
216		pointCount++
217		for _, feature := range s.savedFeatures {
218			if proto.Equal(feature.Location, point) {
219				featureCount++
220			}
221		}
222		if lastPoint != nil {
223			distance += calcDistance(lastPoint, point)
224		}
225		lastPoint = point
226	}
227}
228```
229
230In the method body we use the `RouteGuide_RecordRouteServer`s `Recv()` method to repeatedly read in our client's requests to a request object (in this case a `Point`) until there are no more messages: the server needs to check the the error returned from `Recv()` after each call. If this is `nil`, the stream is still good and it can continue reading; if it's `io.EOF` the message stream has ended and the server can return its `RouteSummary`. If it has any other value, we return the error "as is" so that it'll be translated to an RPC status by the gRPC layer.
231
232#### Bidirectional streaming RPC
233Finally, let's look at our bidirectional streaming RPC `RouteChat()`.
234
235```go
236func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
237	for {
238		in, err := stream.Recv()
239		if err == io.EOF {
240			return nil
241		}
242		if err != nil {
243			return err
244		}
245		key := serialize(in.Location)
246                ... // look for notes to be sent to client
247		for _, note := range s.routeNotes[key] {
248			if err := stream.Send(note); err != nil {
249				return err
250			}
251		}
252	}
253}
254```
255
256This time we get a `RouteGuide_RouteChatServer` stream that, as in our client-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 still writing messages to *their* message stream.
257
258The syntax for reading and writing here is very similar to our client-streaming method, except the server uses the stream's `Send()` method rather than `SendAndClose()` because it's writing multiple responses. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently.
259
260### Starting the server
261
262Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service:
263
264```go
265flag.Parse()
266lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
267if err != nil {
268        log.Fatalf("failed to listen: %v", err)
269}
270grpcServer := grpc.NewServer()
271pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{})
272... // determine whether to use TLS
273grpcServer.Serve(lis)
274```
275To build and start a server, we:
276
2771. Specify the port we want to use to listen for client requests using `lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))`.
2782. Create an instance of the gRPC server using `grpc.NewServer()`.
2793. Register our service implementation with the gRPC server.
2804. Call `Serve()` on the server with our port details to do a blocking wait until the process is killed or `Stop()` is called.
281
282<a name="client"></a>
283## Creating the client
284
285In this section, we'll look at creating a Go client for our `RouteGuide` service. You can see our complete example client code in [grpc-go/examples/route_guide/client/client.go](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/client/client.go).
286
287### Creating a stub
288
289To call service methods, we first need to create a gRPC *channel* to communicate with the server. We create this by passing the server address and port number to `grpc.Dial()` as follows:
290
291```go
292conn, err := grpc.Dial(*serverAddr)
293if err != nil {
294    ...
295}
296defer conn.Close()
297```
298
299You can use `DialOptions` to set the auth credentials (e.g., TLS, GCE credentials, JWT credentials) in `grpc.Dial` if the service you request requires that - however, we don't need to do this for our `RouteGuide` service.
300
301Once the gRPC *channel* is setup, we need a client *stub* to perform RPCs. We get this using the `NewRouteGuideClient` method provided in the `pb` package we generated from our .proto.
302
303```go
304client := pb.NewRouteGuideClient(conn)
305```
306
307### Calling service methods
308
309Now let's look at how we call our service methods. Note that in gRPC-Go, RPCs operate in a blocking/synchronous mode, which means that the RPC call waits for the server to respond, and will either return a response or an error.
310
311#### Simple RPC
312
313Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local method.
314
315```go
316feature, err := client.GetFeature(context.Background(), &pb.Point{409146138, -746188906})
317if err != nil {
318        ...
319}
320```
321
322As you can see, we call the method on the stub we got earlier. In our method parameters we create and populate a request protocol buffer object (in our case `Point`). We also pass a `context.Context` object which lets us change our RPC's behaviour if necessary, such as time-out/cancel an RPC in flight. If the call doesn't return an error, then we can read the response information from the server from the first return value.
323
324```go
325log.Println(feature)
326```
327
328#### Server-side streaming RPC
329
330Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides.
331
332```go
333rect := &pb.Rectangle{ ... }  // initialize a pb.Rectangle
334stream, err := client.ListFeatures(context.Background(), rect)
335if err != nil {
336    ...
337}
338for {
339    feature, err := stream.Recv()
340    if err == io.EOF {
341        break
342    }
343    if err != nil {
344        log.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
345    }
346    log.Println(feature)
347}
348```
349
350As 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 of `RouteGuide_ListFeaturesClient`. The client can use the `RouteGuide_ListFeaturesClient` stream to read the server's responses.
351
352We use the `RouteGuide_ListFeaturesClient`'s `Recv()` method to repeatedly read in the server's responses to a response protocol buffer object (in this case a `Feature`) until there are no more messages: the client needs to check the error `err` returned from `Recv()` after each call. If `nil`, the stream is still good and 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`.
353
354#### Client-side streaming RPC
355
356The client-side streaming method `RecordRoute` is similar to the server-side method, except that we only pass the method a context and get a `RouteGuide_RecordRouteClient` stream back, which we can use to both write *and* read messages.
357
358```go
359// Create a random number of random points
360r := rand.New(rand.NewSource(time.Now().UnixNano()))
361pointCount := int(r.Int31n(100)) + 2 // Traverse at least two points
362var points []*pb.Point
363for i := 0; i < pointCount; i++ {
364	points = append(points, randomPoint(r))
365}
366log.Printf("Traversing %d points.", len(points))
367stream, err := client.RecordRoute(context.Background())
368if err != nil {
369	log.Fatalf("%v.RecordRoute(_) = _, %v", client, err)
370}
371for _, point := range points {
372	if err := stream.Send(point); err != nil {
373		log.Fatalf("%v.Send(%v) = %v", stream, point, err)
374	}
375}
376reply, err := stream.CloseAndRecv()
377if err != nil {
378	log.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil)
379}
380log.Printf("Route summary: %v", reply)
381```
382
383The `RouteGuide_RecordRouteClient` has a `Send()` method that we can use to send requests to the server. Once we've finished writing our client's requests to the stream using `Send()`, we need to call `CloseAndRecv()` on the stream to let gRPC 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 the status is `nil`, then the first return value from `CloseAndRecv()` will be a valid server response.
384
385#### Bidirectional streaming RPC
386
387Finally, let's look at our bidirectional streaming RPC `RouteChat()`. As in the case of `RecordRoute`, we only pass the method a context object and get back a stream that we can use to both write and read messages. However, this time we return values via our method's stream while the server is still writing messages to *their* message stream.
388
389```go
390stream, err := client.RouteChat(context.Background())
391waitc := make(chan struct{})
392go func() {
393	for {
394		in, err := stream.Recv()
395		if err == io.EOF {
396			// read done.
397			close(waitc)
398			return
399		}
400		if err != nil {
401			log.Fatalf("Failed to receive a note : %v", err)
402		}
403		log.Printf("Got message %s at point(%d, %d)", in.Message, in.Location.Latitude, in.Location.Longitude)
404	}
405}()
406for _, note := range notes {
407	if err := stream.Send(note); err != nil {
408		log.Fatalf("Failed to send a note: %v", err)
409	}
410}
411stream.CloseSend()
412<-waitc
413```
414
415The syntax for reading and writing here is very similar to our client-side streaming method, except we use the stream's `CloseSend()` method once we've finished our call. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently.
416
417## Try it out!
418
419To compile and run the server, assuming you are in the folder
420`$GOPATH/src/google.golang.org/grpc/examples/route_guide`, simply:
421
422```sh
423$ go run server/server.go
424```
425
426Likewise, to run the client:
427
428```sh
429$ go run client/client.go
430```
431
432