English | 中文
- Go, should be greater or equal than go1.18.
- tRPC cmdline tools, to generate stub codes from protobuf.
Example code is part of tRPC-Go repo. Clone and change directory to helloworld.
$ git clone --depth 1 git@github.com:trpc-group/trpc-go.git
$ cd trpc-go/examples/helloworld
- Compile and execute the server code:
$ cd server && go run main.go
- From a different terminal, compile and execute the client code:
You will see
$ cd client && go run main.go
Hello world!
displayed as a log.
Congratulations! You’ve just run a client-server application with tRPC-Go.
As you can see, service Greeter
are defined in protobuf ./pb/helloworld.proto
as following:
service Greeter {
rpc Hello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string msg = 1;
}
message HelloReply {
string msg = 1;
}
It has only one method Hello
, which takes HelloRequest
as parameter and returns HelloReply
.
Now, add a new method HelloAgain
, with the same request and response:
service Greeter {
rpc Hello (HelloRequest) returns (HelloReply) {}
rpc HelloAgain (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string msg = 1;
}
message HelloReply {
string msg = 1;
}
Regenerate tRPC code by $ make
in ./pb
directory.
The Makefile calls trpc
which should be installed by prerequisites.
At server side server/main.go
, add codes to implement HelloAgain
:
func (g Greeter) HelloAgain(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) {
log.Infof("got HelloAgain request: %s", req.Msg)
return &pb.HelloReply{Msg: "Hello " + req.Msg + " again!"}, nil
}
At client side client/main.go
, add codes to call HelloAgain
:
rsp, err = c.HelloAgain(context.Background(), &pb.HelloRequest{Msg: "world"})
if err != nil {
log.Error(err)
}
log.Info(rsp.Msg)
Follow the Run the Example
section to re-run your example and you will see Hello world again!
in client log.
- Learn tRPC Design.
- Read basics tutorial to get deeper into tRPC-Go.
- Explore the API reference.