Sobes.tech
Junior — Middle

How to implement message sending in a gRPC service?

sobes.tech AI

Answer from AI

To send a message to a gRPC service in Go, you need to:

  1. Generate Go code from the .proto file describing the service and messages.
  2. Create a gRPC client and connect to the server.
  3. Call the desired service method, passing the message.

Example:

package main

import (
    "context"
    "log"
    "time"

    "google.golang.org/grpc"
    pb "path/to/generated/proto/package"
)

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

    client := pb.NewYourServiceClient(conn)

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

    req := &pb.YourRequest{Message: "Hello, gRPC!"}
    resp, err := client.YourMethod(ctx, req)
    if err != nil {
        log.Fatalf("could not send message: %v", err)
    }

    log.Printf("Response: %s", resp.GetReply())
}

Here, YourServiceClient and YourRequest are generated types from the proto, and YourMethod is the RPC method of the service.