Skip to content
Sign inGet all access
Chapter 1·14 minFree

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:

terminal
buf --version
Output$ go install github.com/bufbuild/buf/cmd/buf@latest$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest$ buf --version1.75.0

Your first .proto

Three declarations, then a service and its messages:

proto/greet/greet.proto
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' | sort
Outputgreetpb/greet.pb.gogreetpb/greet_grpc.pb.go

Two tools ran: protoc-gen-go wrote the message types, protoc-gen-go-grpc the client and server.

buf.gen.yaml
version: v2
plugins:
  - local: protoc-gen-go
    out: .
    opt: module=xz/grpc
  - local: protoc-gen-go-grpc
    out: .
    opt: module=xz/grpc

The protoc equivalent, named once so you can read older tutorials and existing Makefiles:

terminal
true
Output$ protoc -I proto \ --go_out=. --go_opt=module=xz/grpc \ --go-grpc_out=. --go-grpc_opt=module=xz/grpc \ proto/greet/greet.proto

The server

Implement the interface, register it, serve:

server/main.go
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:

client/main.go
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:

terminal
true
Output$ go run ./clienthello ada

Running both

The server blocks, so it needs its own terminal:

terminal
true
Output$ go run ./server(blocks)
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())
}
Outputhello ada

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.go
Output 174 greetpb/greet.pb.go 121 greetpb/greet_grpc.pb.go 295 total

The 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]}'
OutputName string field 1, bytes

The server interface you implemented, and the method that forces the embed:

sed -n '/^type GreeterServer interface/,/^}/p' greetpb/greet_grpc.pb.go
Outputtype GreeterServer interface { SayHello(context.Context, *HelloRequest) (*HelloReply, error) mustEmbedUnimplementedGreeterServer()}

mustEmbedUnimplementedGreeterServer 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:

shown
type GreeterClient interface {
	SayHello(ctx context.Context, in *HelloRequest,
		opts ...grpc.CallOption) (*HelloReply, error)
}