Metadata, Interceptors and Reflection
Headers, middleware, and making a service you can poke at.
How to see what a gRPC server is doing, from both sides.
Metadata is gRPC’s headers
Key-value pairs beside the message, and keys are stored lowercased:
package main
import (
"fmt"
"sort"
"google.golang.org/grpc/metadata"
)
func main() {
md := metadata.Pairs("Request-ID", "abc123")
keys := []string{}
for k := range md {
keys = append(keys, k)
}
sort.Strings(keys)
fmt.Println("stored keys:", keys)
fmt.Println("Get(\"Request-ID\"):", md.Get("Request-ID"))
fmt.Println("Get(\"request-id\"):", md.Get("request-id"))
fmt.Println("map index [Request-ID]:", md["Request-ID"])
fmt.Println("map index [request-id]:", md["request-id"])
}A key ending -bin carries binary, base64-encoded on the wire and raw bytes in Go.
Sending it from a client
AppendToOutgoingContext adds pairs to the context, not the message:
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 main
import (
"context"
"log"
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/reflection"
"xz/grpc/greetpb"
)
type server struct{ greetpb.UnimplementedGreeterServer }
func (s *server) SayHello(ctx context.Context, req *greetpb.HelloRequest) (*greetpb.HelloReply, error) {
md, _ := metadata.FromIncomingContext(ctx)
log.Println("request-id:", md.Get("request-id"))
grpc.SetTrailer(ctx, metadata.Pairs("duration-ms", "7"))
return &greetpb.HelloReply{Message: "hello " + req.GetName()}, nil
}
func logUnary(ctx context.Context, req any, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (any, error) {
log.Println("call:", info.FullMethod)
resp, err := handler(ctx, req)
log.Println("done:", info.FullMethod, "err:", err)
return resp, err
}
func main() {
lis, _ := net.Listen("tcp", ":50055")
s := grpc.NewServer(grpc.ChainUnaryInterceptor(logUnary))
greetpb.RegisterGreeterServer(s, &server{})
reflection.Register(s)
log.Fatal(s.Serve(lis))
}Reading it in a handler
FromIncomingContext on the server, and the response headers come back with grpc.Header:
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"xz/grpc/greetpb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50055",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := greetpb.NewGreeterClient(conn)
ctx := metadata.AppendToOutgoingContext(context.Background(), "Request-ID", "abc123")
var hdr metadata.MD
r, _ := c.SayHello(ctx, &greetpb.HelloRequest{Name: "ada"}, grpc.Header(&hdr))
fmt.Println(r.GetMessage())
fmt.Println("content-type:", hdr.Get("content-type"))
}The server logged the id it received:
trueTrailers
Metadata sent after the response, which is why a stream can report a total:
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"xz/grpc/greetpb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50055",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := greetpb.NewGreeterClient(conn)
var tlr metadata.MD
r, _ := c.SayHello(context.Background(), &greetpb.HelloRequest{Name: "ada"},
grpc.Trailer(&tlr))
fmt.Println(r.GetMessage())
fmt.Println("trailer duration-ms:", tlr.Get("duration-ms"))
}The status code itself is a trailer. That is why a browser cannot speak gRPC — chapter 8.
A unary interceptor
One function, wrapping every call. The signature is the whole idea:
func logUnary(ctx context.Context, req any, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (any, error) {
log.Println("call:", info.FullMethod)
resp, err := handler(ctx, req)
log.Println("done:", info.FullMethod, "err:", err)
return resp, err
}Calling handler runs the next stage; not calling it short-circuits the call. That is how auth
rejects a request before any handler sees it.
Chaining them
ChainUnaryInterceptor takes several, outermost first:
s := grpc.NewServer(grpc.ChainUnaryInterceptor(
recoverPanic,
logUnary,
authenticate,
))It is not browsable
There is no URL. Against the chapter 1 server, grpcurl cannot even list what exists:
trueThe server works perfectly. grpcurl has no .proto file and no way to ask for one.
Turning on reflection
One import and one line fix that:
import "google.golang.org/grpc/reflection"
reflection.Register(s)The server now serves its own schema, so any client can discover it at runtime.
list and describe
Now the same command answers:
grpcurl -plaintext localhost:50055 listAnd describe prints the schema back as proto:
grpcurl -plaintext localhost:50055 describe greet.GreeterThat came from the server, not from a file on your disk.
Calling a method
JSON in, JSON out, converted using the discovered schema:
grpcurl -plaintext -d '{"name": "ada"}' \
localhost:50055 greet.Greeter/SayHelloWithout reflection, pass the schema yourself with -proto proto/greet/greet.proto.
protojson
The same conversion in Go, for when you need the text in a log line:
package main
import (
"fmt"
"google.golang.org/protobuf/encoding/protojson"
"xz/grpc/greetpb"
)
func main() {
j, _ := protojson.Marshal(&greetpb.HelloRequest{Name: "ada"})
fmt.Println(string(j))
}