Unary RPCs
Handlers, getters, the zero-value problem, and additive services.
One request, one response. The shape nine calls in ten have.
The handler signature
A context, a request pointer, a response pointer and an error:
syntax = "proto3";
package greet2;
option go_package = "xz/grpc/g2pb";
service Greeter {
rpc SayHello(HelloRequest) returns (HelloReply);
rpc SayBye(ByeRequest) returns (ByeReply);
}
message HelloRequest { string name = 1; }
message HelloReply { string message = 1; }
message ByeRequest { string name = 1; }
message ByeReply { string message = 1; }package main
import (
"context"
"errors"
"log"
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"xz/grpc/g2pb"
)
type server struct{ g2pb.UnimplementedGreeterServer }
func (s *server) SayHello(ctx context.Context, req *g2pb.HelloRequest) (*g2pb.HelloReply, error) {
if req.GetName() == "" {
return nil, status.Error(codes.InvalidArgument, "name is required")
}
if req.GetName() == "boom" {
return nil, errors.New("nope")
}
return &g2pb.HelloReply{Message: "hello " + req.GetName()}, nil
}
func main() {
lis, _ := net.Listen("tcp", ":50052")
s := grpc.NewServer()
g2pb.RegisterGreeterServer(s, &server{})
log.Fatal(s.Serve(lis))
}Return a response or an error, never both. A non-nil error discards the response.
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"xz/grpc/g2pb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50052",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := g2pb.NewGreeterClient(conn)
r, _ := c.SayHello(context.Background(), &g2pb.HelloRequest{Name: "ada"})
fmt.Println(r.GetMessage())
}Getters, not fields
Every field gets a generated getter, and it is nil-safe:
package main
import (
"fmt"
"xz/grpc/g2pb"
)
func main() {
var req *g2pb.HelloRequest
fmt.Printf("nil getter: %q\n", req.GetName())
}req.Name on that nil pointer panics. req.GetName() returns the zero value.
The zero value problem
A getter cannot tell you whether the field was sent:
package main
import (
"fmt"
"xz/grpc/g2pb"
)
func main() {
a := &g2pb.HelloRequest{Name: ""}
b := &g2pb.HelloRequest{}
fmt.Printf("sent empty: %q len %d\n", a.GetName(), len(a.GetName()))
fmt.Printf("never set: %q len %d\n", b.GetName(), len(b.GetName()))
}Identical, and on the wire they are identical too — a zero-valued field is not transmitted. That is
what chapter 2’s optional exists to fix.
Returning an error
status.Error sets a code the client can branch on:
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"xz/grpc/g2pb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50052",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := g2pb.NewGreeterClient(conn)
_, err := c.SayHello(context.Background(), &g2pb.HelloRequest{})
st, _ := status.FromError(err)
fmt.Println(st.Code(), st.Message())
}A plain Go error loses that. errors.New("nope") arrives as Unknown:
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"xz/grpc/g2pb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50052",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := g2pb.NewGreeterClient(conn)
_, err := c.SayHello(context.Background(), &g2pb.HelloRequest{Name: "boom"})
st, _ := status.FromError(err)
fmt.Println(st.Code(), st.Message())
}UnimplementedServer
SayBye is in the schema and not in the Go code. The call still works:
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"xz/grpc/g2pb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50052",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := g2pb.NewGreeterClient(conn)
_, err := c.SayBye(context.Background(), &g2pb.ByeRequest{Name: "ada"})
st, _ := status.FromError(err)
fmt.Println(st.Code(), st.Message())
}That answer comes from the embedded UnimplementedGreeterServer. Remove the embed and the
same server stops compiling:
trueAdding a method
Add an rpc line, regenerate, and existing code still builds:
package main
import (
"fmt"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"xz/grpc/g2pb"
)
func main() {
_ = g2pb.File_greet2_greet2_proto
d, _ := protoregistry.GlobalFiles.FindDescriptorByName("greet2.Greeter")
svc := d.(protoreflect.ServiceDescriptor)
fmt.Println(svc.FullName())
for i := 0; i < svc.Methods().Len(); i++ {
fmt.Println(" ", svc.Methods().Get(i).Name())
}
}The server keeps compiling because of the embed, and an old client never calls what it does not know about.
One message per method
Every method gets its own request and response type, even when they are identical:
package main
import (
"fmt"
"xz/grpc/g2pb"
)
func main() {
h := (&g2pb.HelloRequest{}).ProtoReflect().Descriptor()
b := (&g2pb.ByeRequest{}).ProtoReflect().Descriptor()
fmt.Println(h.FullName(), "fields:", h.Fields().Len())
fmt.Println(b.FullName(), "fields:", b.Fields().Len())
fmt.Println("interchangeable:", h.FullName() == b.FullName())
}One field each, same shape, and two different names on the wire.