Implementing gRPC in Go on Windows Systems
gRPC operates over HTTP/2 and transmits binary data. This guide covers essential tools and steps for gRPC implementation in Go on Windows.
Required Tools
-
Protocol Buffer Compiler (protoc)
- Downloads: Official Site | GitHub Releases
- Installation: Extract the ZIP and add
protoc.exeto your system PATH (e.g.,D:\Program Files\protoc\bin)
-
Go Plugins
go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28 go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2- Ensure the generated executables are in your PATH (either by copying to
protoc\binor addingGOPATH\bintoo PATH).
- Ensure the generated executables are in your PATH (either by copying to
Project Setup
-
Create a Go project (e.g.,
goGrpcDemo) with directories:config(for Protocol Buffer files)serverclient
-
Install gRPC package:
go get -u google.golang.org/grpc
Protocol Buffer Definition
Create config/helloworld.proto:
syntax = "proto3";
option go_package = "goGrpcDemo/config/helloworld";
package config;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
Generate Go code:
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative helloworld.proto
Server Implementation (server/main.go)
package main
import (
"context"
"flag"
"log"
"net"
pb "goGrpcDemo/config"
"google.golang.org/grpc"
)
type server struct {
pb.UnimplementedGreeterServer
}
func (s *server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello " + req.Name}, nil
}
func main() {
port := flag.Int("port", 50051, "Server port")
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if err != nil {
log.Fatal(err)
}
srv := grpc.NewServer()
pb.RegisterGreeterServer(srv, &server{})
log.Printf("Server listening on %v", lis.Addr())
if err := srv.Serve(lis); err != nil {
log.Fatal(err)
}
}
Client Implementation (client/main.go)
package main
import (
"context"
"flag"
"log"
"time"
pb "goGrpcDemo/config"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func main() {
addr := flag.String("addr", "localhost:50051", "Server address")
name := flag.String("name", "World", "Name to greet")
flag.Parse()
conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
client := pb.NewGreeterClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
reply, err := client.SayHello(ctx, &pb.HelloRequest{Name: *name})
if err != nil {
log.Fatal(err)
}
log.Printf("Response: %s", reply.Message)
}
Run the server and client to test the gRPC communication.