A gRPC client lets one service call operations exposed by another. When an Order service needs to charge a customer, it uses a generated Payment service stub to call Create. Protocol Buffers definitions supply the client-side methods; the services can be written in different supported languages. section 5.2 section 1.1.2
To wire a Go client into a consuming service:
- Add the generated service-stub module as a dependency. Pin a version when reproducible dependency updates matter. section 5.2
- Dial the service address, create a client with the connection, and call its method with a context and request. Close the connection when finished and handle connection or call errors. section 2.5.3
Listing 2.2 Payment stub usage on client side
var opts []grpc.DialOption
conn, err := grpc.Dial(*serverAddr, opts...)
if err != nil {
// handle connection error
}
defer conn.Close()
payment := pb.NewPaymentClient(conn)
result, err := payment.Create(ctx, &CreatePaymentRequest{})
if err != nil {
// handle Payment create error
}
The Payment call is made through NewPaymentClient after grpc.Dial; the connection and call each have an error path. section 2.5.3
A client call can fail or wait too long for a response. Pass a context with a timeout to bound the wait, and consider retries based on response status or error type. These choices matter when a failed payment call could leave an order pending. section 2.5.3 section 5.0
ctx, cancel := context.WithTimeout(context.Background(),
10 * time.Second)
defer cancel() #1
payment := pb.NewPaymentClient(conn)
result, err := payment.Create(ctx, &CreatePaymentRequest{}) #2
if err != nil {
// handle Payment create an error
}
A ten-second context timeout bounds the Create call, with deferred cancellation to release the context. section 2.5.3














