Exploring Client-Side Interaction with gRPC in Golang! 🌟

Author: azar m

November 3, 2023

2 min read

📢 Part 5: Exploring Client-Side Interaction with gRPC in Golang! 🌟

Welcome to the next installment of our gRPC in Golang series! In this article, we'll dive into the client-side of gRPC, showcasing how to create a Golang client that communicates with our previously implemented PingService. Let's walk through the provided code and understand the various components.

Understanding the Client Implementation:

Client Setup:

go

package main import ( "context" "fmt" "log" "time" "github.com/MrAzharuddin/grpc_tutorial/pb" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) var ( serverAddress = "localhost:50051" ) func main() { // Set up a connection to the server. conn, err := grpc.Dial(serverAddress, grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { log.Fatalf("Could not connect to the server: %v", err) } defer conn.Close()

In this section, a connection is established to the gRPC server. The grpc.Dial function is used to set up this connection, with grpc.WithTransportCredentials(insecure.NewCredentials()) specifying that we're using an insecure connection. In a production environment, you would use secure credentials.

Creating a PingService Client:

go

// Create a PingService client client := pb.NewPingServiceClient(conn)

The pb.NewPingServiceClient function is generated from the Proto file. It provides a client interface to invoke methods defined in the PingService.

Invoking the Ping RPC:

go

// Call Ping RPC pingRequest := &pb.PingRequest{} ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() pingResponse, err := client.Ping(ctx, pingRequest) if err != nil { log.Fatalf("Error calling Ping RPC: %v", err) }

Here, we create a PingRequest and initiate a context with a timeout. The client.Ping method is then invoked with these parameters, making a request to the PingService on the server.

Handling Responses:

go

// Print the response fmt.Println("Server Response:", pingResponse.Message) }

The server's response is then printed, completing the client-side interaction.

Running the Client:

Make sure your server is running, and then execute your client. This code initiates a connection to the server, invokes the Ping RPC, and prints the server's response.

Conclusion:

In this article, we've explored the client-side of gRPC in Golang, focusing on connecting to a server and invoking an RPC method. Understanding both the server and client sides is crucial for developing efficient and robust microservices.

Source code: https://github.com/MrAzharuddin/grpc_tutorial

Stay tuned for the next part, where we'll delve into more advanced features of gRPC in Golang!