Go gRPC hello world。
安裝Protocol Buffer Compiler
參考「Windows 11 安裝Protocol Buffer Compiler」
安裝Protocol Compiler的Go plugins
在命令列輸入go install google.golang.org/protobuf/cmd/protoc-gen-go@latest和
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest。
$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go: downloading google.golang.org/protobuf v1.36.6
$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
go: downloading google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1
go: downloading google.golang.org/grpc v1.71.1
go: downloading google.golang.org/protobuf v1.34.1
建立proto檔
在專案根目錄下新增hello.proto,內容如下。
hello.proto
syntax = "proto3";
package hello;
option go_package = "./hello_pb";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
內容說明:
syntax = "proto3"- 宣告此.proto使用proto3語法package hello- 定義此.proto的命名空間,例如在其他.proto的message中可使用hello.HelloRequestoption go_package = "./hello_pb"- 定義protoc產生gRPC程式碼時的路徑,./hello_pb為執行protoc命令所在目錄下的hello_pb目錄。service Greeter {...}- 定義一個名為"Greeter"的RPC(遠端程序呼叫)服務介面,服務由gRPC server端實作。message HelloRequest {...}- 定義一個名為"HelloRequest"的訊息交換格式,反映到protoc產生在hello.pb.go中的HelloRequeststruct。string name = 1代表此訊息中的一個欄位名稱為"name",型態為string(字串),= 1的數字為欄位的唯一編號。message HelloReply {...}- 定義一個名為"HelloReply"的訊息交換格式,反映到protoc產生在hello.pb.go中的HelloReplystruct。
產生gRPC的go程式碼
在專案根目錄命令列執行protoc --go_out=. --go-grpc_out=. hello.proto,根據hello.proto產生gRPC的程式碼。
$ protoc --go_out=. --go-grpc_out=. hello.proto
執行後在專案根目錄下會產生hello_pb目錄,裡面有hello.pb.go和hello_grpc.pb.go兩個檔案。
建立gRPC Server
在專案根目錄下新增cmd/server/server.go
server.go
package main
import (
"context"
"log"
"net"
pb "abc.com/demo/hello_pb"
"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: %s", req.Name)
return &pb.HelloReply{Message: "Hello, " + req.Name + "!"}, 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("gRPC server listening on port 50051...")
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
建立gRPC Client
在專案根目錄下新增cmd/client/client.go
client.go
package main
import (
"context"
"log"
"time"
pb "abc.com/demo/hello_pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func main() {
// conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure(), grpc.WithBlock())
conn, err := grpc.NewClient("localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
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()
r, err := c.SayHello(ctx, &pb.HelloRequest{Name: "World"})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)
}
在專案根目錄命令列執行go mod tidy下載依賴module。
測試
在專案根目錄以命令列執行go run cmd/server/server.go。
$ go run cmd/server/server.go
2025/04/22 14:54:41 gRPC server listening on port 50051...
在專案根目錄另開一個命令列執行go run cmd/client/client.go。
$ go run cmd/client/client.go
2025/04/22 14:56:16 Greeting: Hello, World!
回到執行server.go的命令列視窗,出現以下訊息。
2025/04/22 14:56:16 Received: World
沒有留言:
張貼留言