Getting Started
A working call before any theory: proto, codegen, server, client.
A call that works, before any explanation of why it is shaped this way.
What gRPC replaces
You write a schema, a tool writes the client and server types:
| REST | gRPC | |
|---|---|---|
| Schema | docs, or nobody’s head | a .proto file |
| Client code | you write it | generated |
| Payload | JSON text | binary |
Debuggable with curl |
yes | no |
| Streaming | bolted on | four call shapes |
Nothing here is advocacy. Chapter 8 says where REST wins.
Installing the toolchain
Three binaries, all into ~/go/bin:
buf --versionYour first .proto
Three declarations, then a service and its messages:
syntax = "proto3";
package greet;
option go_package = "xz/grpc/greetpb";
service Greeter {
rpc SayHello(HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}package greet names the service on the wire. option go_package is a Go-specific instruction in
a language-neutral file.
Generating the code
One command reads the directory and writes Go:
buf generate proto
find greetpb -name '*.go' | sortTwo tools ran: protoc-gen-go wrote the message types, protoc-gen-go-grpc the client and
server.
version: v2
plugins:
- local: protoc-gen-go
out: .
opt: module=xz/grpc
- local: protoc-gen-go-grpc
out: .
opt: module=xz/grpcThe protoc equivalent, named once so you can read older tutorials and existing Makefiles:
trueThe server
Implement the interface, register it, serve:
package main
import (
"context"
"log"
"net"
"google.golang.org/grpc"
"xz/grpc/greetpb"
)
type server struct {
greetpb.UnimplementedGreeterServer
}
func (s *server) SayHello(ctx context.Context, req *greetpb.HelloRequest) (*greetpb.HelloReply, error) {
return &greetpb.HelloReply{Message: "hello " + req.GetName()}, nil
}
func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatal(err)
}
s := grpc.NewServer()
greetpb.RegisterGreeterServer(s, &server{})
log.Fatal(s.Serve(lis))
}net.Listen gives a plain TCP socket and gRPC takes it over. No router, no path.
The client
A connection, a typed client, a method call:
package main
import (
"context"
"fmt"
"log"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"xz/grpc/greetpb"
)
func main() {
conn, err := grpc.NewClient("localhost:50051",
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
c := greetpb.NewGreeterClient(conn)
r, err := c.SayHello(context.Background(), &greetpb.HelloRequest{Name: "ada"})
if err != nil {
log.Fatal(err)
}
fmt.Println(r.GetMessage())
}SayHello looks local and takes a context.Context first. That context is chapter 5.
Naming insecure is required. There is no default:
trueRunning both
The server blocks, so it needs its own terminal:
truepackage main
import (
"context"
"fmt"
"log"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"xz/grpc/greetpb"
)
func main() {
conn, err := grpc.NewClient("localhost:50051",
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
c := greetpb.NewGreeterClient(conn)
r, err := c.SayHello(context.Background(), &greetpb.HelloRequest{Name: "ada"})
if err != nil {
log.Fatal(err)
}
fmt.Println(r.GetMessage())
}A method on a struct, a response over a socket, no URL anywhere.
What got generated
Nearly 300 lines you did not write:
wc -l greetpb/greet.pb.go greetpb/greet_grpc.pb.goThe message struct, with the field number in its tag:
grep 'Name ' greetpb/greet.pb.go | head -1 \
| awk -F'"' '{split($1,a," "); split($2,b,","); \
printf "%s %s field %s, %s\n", a[1], a[2], b[2], b[1]}'The server interface you implemented, and the method that forces the embed:
sed -n '/^type GreeterServer interface/,/^}/p' greetpb/greet_grpc.pb.gomustEmbedUnimplementedGreeterServer is unexported, so only generated code satisfies it. That is
how the embed is enforced.
The client interface is the mirror image, with call options added:
type GreeterClient interface {
SayHello(ctx context.Context, in *HelloRequest,
opts ...grpc.CallOption) (*HelloReply, error)
}