How do I build unary RPCs in Go?

Building unary RPCs in Go involves creating a server and a client that communicate over gRPC protocol. Unary RPCs are simple requests where a client sends a single request to the server and gets back a single response.

package main

import (
    "context"
    "fmt"
    "log"
    "net"

    pb "path/to/your/proto/package" // Update with your protobuf package path
    "google.golang.org/grpc"
)

// server is used to implement your service defined in your .proto file
type server struct {
    pb.UnimplementedYourServiceServer // replace YourService with your service name
}

// SayHello implements the SayHello method of the service
func (s *server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {
    log.Printf("Received request for: %s", req.Name)
    return &pb.HelloResponse{Message: "Hello " + req.Name}, nil
}

func main() {
    // Create a TCP listener on port 50051
    lis, err := net.Listen("tcp", ":50051")
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }

    // Create a new gRPC server
    s := grpc.NewServer()
    pb.RegisterYourServiceServer(s, &server{}) // replace YourService with your service name

    // Start the server
    fmt.Println("Server is listening on port 50051...")
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}
    

Go gRPC unary RPC Go gRPC example Go server implementation client-server communication