Some edits/rewriting of Go tutorial

pull/3109/head
Lisa Carey 10 years ago
parent 8b367bc965
commit c4a3300867
  1. 113
      go/gotutorial.md

@ -37,7 +37,7 @@ Our first step (as you'll know from [Getting started](https://github.com/grpc/gr
To define a service, you specify a named `service` in your .proto file: To define a service, you specify a named `service` in your .proto file:
``` ```proto
service RouteGuide { service RouteGuide {
... ...
} }
@ -46,13 +46,13 @@ service RouteGuide {
Then 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: Then 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:
- 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. - 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.
``` ```proto
// Obtains the feature at a given position. // Obtains the feature at a given position.
rpc GetFeature(Point) returns (Feature) {} rpc GetFeature(Point) returns (Feature) {}
``` ```
- 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. - 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.
``` ```proto
// Obtains the Features available within the given Rectangle. Results are // Obtains the Features available within the given Rectangle. Results are
// streamed rather than returned at once (e.g. in a response message with a // streamed rather than returned at once (e.g. in a response message with a
// repeated field), as the rectangle may cover a large area and contain a // repeated field), as the rectangle may cover a large area and contain a
@ -61,21 +61,21 @@ Then you define `rpc` methods inside your service definition, specifying their r
``` ```
- 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 server-side streaming method by placing the `stream` keyword before the *request* type. - 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 server-side streaming method by placing the `stream` keyword before the *request* type.
``` ```proto
// Accepts a stream of Points on a route being traversed, returning a // Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed. // RouteSummary when traversal is completed.
rpc RecordRoute(stream Point) returns (RouteSummary) {} rpc RecordRoute(stream Point) returns (RouteSummary) {}
``` ```
- 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. - 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.
``` ```proto
// Accepts a stream of RouteNotes sent while a route is being traversed, // Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users). // while receiving other RouteNotes (e.g. from other users).
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
``` ```
Our .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: Our .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:
``` ```proto
// Points are represented as latitude-longitude pairs in the E7 representation // Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer). // (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in // Latitudes should be in the range +/- 90 degrees and longitude should be in
@ -103,7 +103,7 @@ which actually runs:
$ protoc --go_out=plugins=grpc:. route_guide.proto $ protoc --go_out=plugins=grpc:. route_guide.proto
``` ```
Running this command generates the following files in your current directory: Running this command generates the following file in your current directory:
- `route_guide.pb.go` - `route_guide.pb.go`
This contains: This contains:
@ -117,7 +117,7 @@ This contains:
First 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!). First 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!).
There are two parts to make our `RouteGuide` service do its job: 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. - 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 to the right service implementation. - Running a gRPC server to listen for requests from clients and dispatch them to the right service implementation.
@ -154,6 +154,7 @@ func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error
... ...
``` ```
#### Simple RPC
`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`. `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`.
```go ```go
@ -168,9 +169,10 @@ func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb
} }
``` ```
The method is passed a context object for the RPC, 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. The 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.
Now let's look at something a bit more complicated - a streaming RPC. `ListFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client. #### Server-side streaming RPC
Now 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.
```go ```go
func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error { func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
@ -185,26 +187,49 @@ func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide
} }
``` ```
As 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. 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've finished writing responses. Should there be any error happened in this call, we return a non-`nil` error and the gRPC layer will translate it into an appropriate RPC status to be sent on the wire. As 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.
If you look at the client-side streaming method `RecordRoute` you'll see it's quite similar, except this time we don't have to pass the method a request. Instead, we pass in a `RouteGuide_RecordRouteServer`, through which we can receive client messages using its `Recv()` method. 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'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.
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 `Read()` after each call. If `nil`, the stream is still good and it can continue reading; if it's `io.EOF` the message stream has ended. Otherwise, we return the error as is so that it'll be translated to an RPC status by the gRPC layer. #### Client-side streaming RPC
Now 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.
```go ```go
for { func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error {
point, err := stream.Recv() var pointCount, featureCount, distance int32
if err == io.EOF { var lastPoint *pb.Point
return stream.SendAndClose(&pb.RouteSummary{ startTime := time.Now()
... for {
}) point, err := stream.Recv()
} if err == io.EOF {
if err != nil { endTime := time.Now()
return err return stream.SendAndClose(&pb.RouteSummary{
} PointCount: pointCount,
... FeatureCount: featureCount,
Distance: distance,
ElapsedTime: int32(endTime.Sub(startTime).Seconds()),
})
}
if err != nil {
return err
}
pointCount++
for _, feature := range s.savedFeatures {
if proto.Equal(feature.Location, point) {
featureCount++
}
}
if lastPoint != nil {
distance += calcDistance(lastPoint, point)
}
lastPoint = point
}
} }
``` ```
In 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 `Read()` 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.
#### Bidirectional streaming RPC
Finally, let's look at our bidirectional streaming RPC `RouteChat()`. Finally, let's look at our bidirectional streaming RPC `RouteChat()`.
```go ```go
@ -228,7 +253,9 @@ func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error
} }
``` ```
This time we get a `RouteGuide_RouteChatServer` that can be used to read *and* write messages. The syntax for reading and writing here is exactly the same as for our client-streaming and server-streaming methods. 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. This 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.
The 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.
### Starting the server ### Starting the server
@ -245,12 +272,12 @@ pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{})
... // determine whether to use TLS ... // determine whether to use TLS
grpcServer.Serve(lis) grpcServer.Serve(lis)
``` ```
As you can see, we build our server using `grpc.NewServer()`. To do this, we: To build and start a server, we:
1. Specify the port we want to use to listen for client requests using `lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))`. 1. Specify the port we want to use to listen for client requests using `lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))`.
2. Create an instance of the gRPC server, by `grpc.NewServer()`. 2. Create an instance of the gRPC server using `grpc.NewServer()`.
3. Register our service implementation with the gRPC server. 3. Register our service implementation with the gRPC server.
4. Call `Serve()` on the server to do a blocking wait until process is killed or `Stop()` is called. 4. Call `Serve()` on the server with our port details to do a blocking wait until the process is killed or `Stop()` is called.
<a name="client"></a> <a name="client"></a>
## Creating the client ## Creating the client
@ -259,7 +286,7 @@ In this section, we'll look at creating a Go client for our `RouteGuide` service
### Creating a stub ### Creating a stub
To call service methods, we first need to create a gRPC "channel* as the message communication media by simply passing the server address and port number as follows: To 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:
```go ```go
conn, err := grpc.Dial(*serverAddr) conn, err := grpc.Dial(*serverAddr)
@ -269,9 +296,9 @@ if err != nil {
defer conn.Close() defer conn.Close()
``` ```
We 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. You 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.
Once the gRPC *channel* is setup, we need a client *stub* to perform RPCs by using the `NewRouteGuideClient` method provided in the `pb` package we generated from our .proto. Once 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.
```go ```go
client := pb.NewRouteGuideClient(conn) client := pb.NewRouteGuideClient(conn)
@ -279,7 +306,7 @@ client := pb.NewRouteGuideClient(conn)
### Calling service methods ### Calling service methods
Now let's look at how we call our service methods. Note that in gRPC-Go, RPC operates 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. Now 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.
#### Simple RPC #### Simple RPC
@ -292,15 +319,15 @@ if err != nil {
} }
``` ```
As you can see, we create and populate a request protocol buffer object (in our case `Point`). We also pass a `context.Context` object which allows us to time-out/cancel an RPC in flight. Finally, we call the method on the stub, passing it the context, and request. If the call doesn't return an error, then we can read the response information from the server from the first return value. As 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.
```go ```go
log.Println(feature) log.Println(feature)
``` ```
#### Streaming RPCs #### Server-side streaming RPC
Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s from server to client: Here'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.
```go ```go
rect := &pb.Rectangle{ ... } // initialize a pb.Rectangle rect := &pb.Rectangle{ ... } // initialize a pb.Rectangle
@ -320,9 +347,13 @@ for {
} }
``` ```
As in simple RPC, we pass the method a context and a request. But instead of getting a response object back, we get back an instance of `RouteGuide_ListFeaturesClient`. The client can use the `RouteGuide_ListFeaturesClient` to read the server's responses. We 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`. 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 of `RouteGuide_ListFeaturesClient`. The client can use the `RouteGuide_ListFeaturesClient` stream to read the server's responses.
We 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`.
The client-side streaming method `RecordRoute` is similar, except that we only pass the method a context and get a `RouteGuide_RecordRouteClient` back, which has a `Send()` method that we can use to send requests to the server. #### Client-side streaming RPC
The 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.
```go ```go
// Create a random number of random points // Create a random number of random points
@ -349,9 +380,11 @@ if err != nil {
log.Printf("Route summary: %v", reply) log.Printf("Route summary: %v", reply)
``` ```
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 will be a valid server response. The `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.
#### Bidirectional streaming RPC
Finally, let's look at our bidirectional streaming RPC `RouteChat()`. As in the case of `RecordRoute`, we only pass the method a context object. But in this case we get back a `RouteGuide_RouteChatClient`, which we can use to both write *and* read messages. Finally, 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.
```go ```go
stream, err := client.RouteChat(context.Background()) stream, err := client.RouteChat(context.Background())
@ -379,6 +412,8 @@ stream.CloseSend()
<-waitc <-waitc
``` ```
The 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.
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. 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.
## Try it out! ## Try it out!

Loading…
Cancel
Save