Prerequisites

Before you start, ensure you have the following installed:

  • Go (version 1.13 or later)
  • Protocol Buffers (protoc) compiler
  • gRPC Go library

You can install the gRPC Go library using the following command:

go get google.golang.org/grpc

Step 1: Define Your Service

Create a new directory for your project and navigate into it. Inside, create a file named service.proto to define your gRPC service using Protocol Buffers.

syntax = "proto3";

package greeter;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings.
message HelloReply {
  string message = 1;
}

Explanation

  • service Greeter: This defines the service named Greeter.
  • rpc SayHello: This defines a remote procedure call named SayHello, which takes a HelloRequest and returns a HelloReply.
  • message HelloRequest: This message structure encapsulates the input parameter (the user's name).
  • message HelloReply: This message structure encapsulates the output parameter (the greeting message).

Step 2: Generate Go Code from the Proto File

To generate the Go code, run the following command in your terminal:

protoc --go_out=. --go-grpc_out=. service.proto

This command generates two files: service.pb.go and service_grpc.pb.go, which contain the necessary code for your gRPC service.

Step 3: Implement the Server

Create a new file named server.go and implement the server logic.

package main

import (
    "context"
    "log"
    "net"

    pb "path/to/your/generated/proto/files" // Update with the correct path
    "google.golang.org/grpc"
)

type server struct {
    pb.UnimplementedGreeterServer
}

func (s *server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) {
    log.Printf("Received: %v", req.GetName())
    return &pb.HelloReply{Message: "Hello " + req.GetName()}, nil
}

func main() {
    lis, err := net.Listen("tcp", ":50051")
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }
    s := grpc.NewServer()
    pb.RegisterGreeterServer(s, &server{})
    log.Println("Server is running on port 50051...")
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

Explanation

  • server struct: This struct implements the GreeterServer interface.
  • SayHello method: This method handles incoming requests, logs the received name, and returns a greeting message.
  • main function: This function sets up the TCP listener and starts the gRPC server.

Step 4: Implement the Client

Create another file named client.go to implement the client that will communicate with the gRPC server.

package main

import (
    "context"
    "log"
    "time"

    pb "path/to/your/generated/proto/files" // Update with the correct path
    "google.golang.org/grpc"
)

func main() {
    conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure(), grpc.WithBlock())
    if err != nil {
        log.Fatalf("did not connect: %v", err)
    }
    defer conn.Close()

    c := pb.NewGreeterClient(conn)

    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()

    name := "World"
    res, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
    if err != nil {
        log.Fatalf("could not greet: %v", err)
    }
    log.Printf("Greeting: %s", res.GetMessage())
}

Explanation

  • grpc.Dial: This function establishes a connection to the server.
  • NewGreeterClient: This creates a new client for the Greeter service.
  • SayHello: This calls the SayHello method on the server and logs the response.

Step 5: Run the Application

  1. Open two terminal windows.
  2. In the first terminal, run the server:
    go run server.go
  1. In the second terminal, run the client:
    go run client.go

You should see the client output something like:

Greeting: Hello World

Best Practices

  1. Error Handling: Always handle errors gracefully to avoid unexpected crashes.
  2. Context Management: Use context to manage timeouts and cancellations effectively.
  3. Security: Consider using TLS for secure communication in production environments.
  4. Versioning: Version your API to maintain backward compatibility as you evolve your service.

Learn more with useful resources