examples: metadata (#2500)
This commit is contained in:
@ -77,8 +77,7 @@ func (s *server) SomeRPC(ctx context.Context, in *pb.SomeRequest) (*pb.SomeRespo
|
||||
|
||||
## Sending and receiving metadata - client side
|
||||
|
||||
[//]: # "TODO: uncomment next line after example source added"
|
||||
[//]: # "Real metadata sending and receiving examples are available [here](TODO:example_dir)."
|
||||
Client side metadata sending and receiving examples are available [here](../examples/features/metadata/client/main.go).
|
||||
|
||||
### Sending metadata
|
||||
|
||||
@ -165,8 +164,7 @@ trailer := stream.Trailer()
|
||||
|
||||
## Sending and receiving metadata - server side
|
||||
|
||||
[//]: # "TODO: uncomment next line after example source added"
|
||||
[//]: # "Real metadata sending and receiving examples are available [here](TODO:example_dir)."
|
||||
Server side metadata sending and receiving examples are available [here](../examples/features/metadata/server/main.go).
|
||||
|
||||
### Receiving metadata
|
||||
|
||||
|
18
examples/features/metadata/README.md
Normal file
18
examples/features/metadata/README.md
Normal file
@ -0,0 +1,18 @@
|
||||
# Metadata example
|
||||
|
||||
This example shows how to set and read metadata in RPC headers and trailers.
|
||||
Please see
|
||||
[grpc-metadata.md](https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md)
|
||||
for more information.
|
||||
|
||||
## Start the server
|
||||
|
||||
```
|
||||
go run server/main.go
|
||||
```
|
||||
|
||||
## Run the client
|
||||
|
||||
```
|
||||
go run client/main.go
|
||||
```
|
306
examples/features/metadata/client/main.go
Normal file
306
examples/features/metadata/client/main.go
Normal file
@ -0,0 +1,306 @@
|
||||
/*
|
||||
*
|
||||
* Copyright 2018 gRPC authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
// Binary client is an example client.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
pb "google.golang.org/grpc/examples/features/proto/echo"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
var addr = flag.String("addr", "localhost:50051", "the address to connect to")
|
||||
|
||||
const (
|
||||
timestampFormat = time.StampNano // "Jan _2 15:04:05.000"
|
||||
streamingCount = 10
|
||||
)
|
||||
|
||||
func unaryCallWithMetadata(c pb.EchoClient, message string) {
|
||||
fmt.Printf("--- unary ---\n")
|
||||
// Create metadata and context.
|
||||
md := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
|
||||
ctx := metadata.NewOutgoingContext(context.Background(), md)
|
||||
|
||||
// Make RPC using the context with the metadata.
|
||||
var header, trailer metadata.MD
|
||||
r, err := c.UnaryEcho(ctx, &pb.EchoRequest{Message: message}, grpc.Header(&header), grpc.Trailer(&trailer))
|
||||
if err != nil {
|
||||
log.Fatalf("failed to call UnaryEcho: %v", err)
|
||||
}
|
||||
|
||||
if t, ok := header["timestamp"]; ok {
|
||||
fmt.Printf("timestamp from header:\n")
|
||||
for i, e := range t {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
} else {
|
||||
log.Fatal("timestamp expected but doesn't exist in header")
|
||||
}
|
||||
if l, ok := header["location"]; ok {
|
||||
fmt.Printf("location from header:\n")
|
||||
for i, e := range l {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
} else {
|
||||
log.Fatal("location expected but doesn't exist in header")
|
||||
}
|
||||
fmt.Printf("response:\n")
|
||||
fmt.Printf(" - %s\n", r.Message)
|
||||
|
||||
if t, ok := trailer["timestamp"]; ok {
|
||||
fmt.Printf("timestamp from trailer:\n")
|
||||
for i, e := range t {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
} else {
|
||||
log.Fatal("timestamp expected but doesn't exist in trailer")
|
||||
}
|
||||
}
|
||||
|
||||
func serverStreamingWithMetadata(c pb.EchoClient, message string) {
|
||||
fmt.Printf("--- server streaming ---\n")
|
||||
// Create metadata and context.
|
||||
md := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
|
||||
ctx := metadata.NewOutgoingContext(context.Background(), md)
|
||||
|
||||
// Make RPC using the context with the metadata.
|
||||
stream, err := c.ServerStreamingEcho(ctx, &pb.EchoRequest{Message: message})
|
||||
if err != nil {
|
||||
log.Fatalf("failed to call ServerStreamingEcho: %v", err)
|
||||
}
|
||||
|
||||
// Read the header when the header arrives.
|
||||
header, err := stream.Header()
|
||||
if err != nil {
|
||||
log.Fatalf("failed to get header from stream: %v", err)
|
||||
}
|
||||
// Read metadata from server's header.
|
||||
if t, ok := header["timestamp"]; ok {
|
||||
fmt.Printf("timestamp from header:\n")
|
||||
for i, e := range t {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
} else {
|
||||
log.Fatal("timestamp expected but doesn't exist in header")
|
||||
}
|
||||
if l, ok := header["location"]; ok {
|
||||
fmt.Printf("location from header:\n")
|
||||
for i, e := range l {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
} else {
|
||||
log.Fatal("location expected but doesn't exist in header")
|
||||
}
|
||||
|
||||
// Read all the responses.
|
||||
var rpcStatus error
|
||||
fmt.Printf("response:\n")
|
||||
for {
|
||||
r, err := stream.Recv()
|
||||
if err != nil {
|
||||
rpcStatus = err
|
||||
break
|
||||
}
|
||||
fmt.Printf(" - %s\n", r.Message)
|
||||
}
|
||||
if rpcStatus != io.EOF {
|
||||
log.Fatalf("failed to finish server streaming: %v", rpcStatus)
|
||||
}
|
||||
|
||||
// Read the trailer after the RPC is finished.
|
||||
trailer := stream.Trailer()
|
||||
// Read metadata from server's trailer.
|
||||
if t, ok := trailer["timestamp"]; ok {
|
||||
fmt.Printf("timestamp from trailer:\n")
|
||||
for i, e := range t {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
} else {
|
||||
log.Fatal("timestamp expected but doesn't exist in trailer")
|
||||
}
|
||||
}
|
||||
|
||||
func clientStreamWithMetadata(c pb.EchoClient, message string) {
|
||||
fmt.Printf("--- client streaming ---\n")
|
||||
// Create metadata and context.
|
||||
md := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
|
||||
ctx := metadata.NewOutgoingContext(context.Background(), md)
|
||||
|
||||
// Make RPC using the context with the metadata.
|
||||
stream, err := c.ClientStreamingEcho(ctx)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to call ClientStreamingEcho: %v\n", err)
|
||||
}
|
||||
|
||||
// Read the header when the header arrives.
|
||||
header, err := stream.Header()
|
||||
if err != nil {
|
||||
log.Fatalf("failed to get header from stream: %v", err)
|
||||
}
|
||||
// Read metadata from server's header.
|
||||
if t, ok := header["timestamp"]; ok {
|
||||
fmt.Printf("timestamp from header:\n")
|
||||
for i, e := range t {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
} else {
|
||||
log.Fatal("timestamp expected but doesn't exist in header")
|
||||
}
|
||||
if l, ok := header["location"]; ok {
|
||||
fmt.Printf("location from header:\n")
|
||||
for i, e := range l {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
} else {
|
||||
log.Fatal("location expected but doesn't exist in header")
|
||||
}
|
||||
|
||||
// Send all requests to the server.
|
||||
for i := 0; i < streamingCount; i++ {
|
||||
if err := stream.Send(&pb.EchoRequest{Message: message}); err != nil {
|
||||
log.Fatalf("failed to send streaming: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Read the response.
|
||||
r, err := stream.CloseAndRecv()
|
||||
if err != nil {
|
||||
log.Fatalf("failed to CloseAndRecv: %v\n", err)
|
||||
}
|
||||
fmt.Printf("response:\n")
|
||||
fmt.Printf(" - %s\n\n", r.Message)
|
||||
|
||||
// Read the trailer after the RPC is finished.
|
||||
trailer := stream.Trailer()
|
||||
// Read metadata from server's trailer.
|
||||
if t, ok := trailer["timestamp"]; ok {
|
||||
fmt.Printf("timestamp from trailer:\n")
|
||||
for i, e := range t {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
} else {
|
||||
log.Fatal("timestamp expected but doesn't exist in trailer")
|
||||
}
|
||||
}
|
||||
|
||||
func bidirectionalWithMetadata(c pb.EchoClient, message string) {
|
||||
fmt.Printf("--- bidirectional ---\n")
|
||||
// Create metadata and context.
|
||||
md := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
|
||||
ctx := metadata.NewOutgoingContext(context.Background(), md)
|
||||
|
||||
// Make RPC using the context with the metadata.
|
||||
stream, err := c.BidirectionalStreamingEcho(ctx)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to call BidirectionalStreamingEcho: %v\n", err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
// Read the header when the header arrives.
|
||||
header, err := stream.Header()
|
||||
if err != nil {
|
||||
log.Fatalf("failed to get header from stream: %v", err)
|
||||
}
|
||||
// Read metadata from server's header.
|
||||
if t, ok := header["timestamp"]; ok {
|
||||
fmt.Printf("timestamp from header:\n")
|
||||
for i, e := range t {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
} else {
|
||||
log.Fatal("timestamp expected but doesn't exist in header")
|
||||
}
|
||||
if l, ok := header["location"]; ok {
|
||||
fmt.Printf("location from header:\n")
|
||||
for i, e := range l {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
} else {
|
||||
log.Fatal("location expected but doesn't exist in header")
|
||||
}
|
||||
|
||||
// Send all requests to the server.
|
||||
for i := 0; i < streamingCount; i++ {
|
||||
if err := stream.Send(&pb.EchoRequest{Message: message}); err != nil {
|
||||
log.Fatalf("failed to send streaming: %v\n", err)
|
||||
}
|
||||
}
|
||||
stream.CloseSend()
|
||||
}()
|
||||
|
||||
// Read all the responses.
|
||||
var rpcStatus error
|
||||
fmt.Printf("response:\n")
|
||||
for {
|
||||
r, err := stream.Recv()
|
||||
if err != nil {
|
||||
rpcStatus = err
|
||||
break
|
||||
}
|
||||
fmt.Printf(" - %s\n", r.Message)
|
||||
}
|
||||
if rpcStatus != io.EOF {
|
||||
log.Fatalf("failed to finish server streaming: %v", rpcStatus)
|
||||
}
|
||||
|
||||
// Read the trailer after the RPC is finished.
|
||||
trailer := stream.Trailer()
|
||||
// Read metadata from server's trailer.
|
||||
if t, ok := trailer["timestamp"]; ok {
|
||||
fmt.Printf("timestamp from trailer:\n")
|
||||
for i, e := range t {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
} else {
|
||||
log.Fatal("timestamp expected but doesn't exist in trailer")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
const message = "this is examples/metadata"
|
||||
|
||||
func main() {
|
||||
// Set up a connection to the server.
|
||||
conn, err := grpc.Dial(*addr, grpc.WithInsecure())
|
||||
if err != nil {
|
||||
log.Fatalf("did not connect: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
c := pb.NewEchoClient(conn)
|
||||
|
||||
unaryCallWithMetadata(c, message)
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
serverStreamingWithMetadata(c, message)
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
clientStreamWithMetadata(c, message)
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
bidirectionalWithMetadata(c, message)
|
||||
}
|
207
examples/features/metadata/server/main.go
Normal file
207
examples/features/metadata/server/main.go
Normal file
@ -0,0 +1,207 @@
|
||||
/*
|
||||
*
|
||||
* Copyright 2018 gRPC authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
// Binary server is an example server.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
pb "google.golang.org/grpc/examples/features/proto/echo"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
var port = flag.Int("port", 50051, "the port to serve on")
|
||||
|
||||
const (
|
||||
timestampFormat = time.StampNano
|
||||
smallDuration = time.Second
|
||||
streamingCount = 10
|
||||
)
|
||||
|
||||
type server struct{}
|
||||
|
||||
func (s *server) UnaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) {
|
||||
fmt.Printf("--- UnaryEcho ---\n")
|
||||
// Create trailer in defer to record function return time.
|
||||
defer func() {
|
||||
trailer := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
|
||||
grpc.SetTrailer(ctx, trailer)
|
||||
}()
|
||||
|
||||
// Read metadata from client.
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, status.Errorf(codes.DataLoss, "UnaryEcho: failed to get metadata")
|
||||
}
|
||||
if t, ok := md["timestamp"]; ok {
|
||||
fmt.Printf("timestamp from metadata:\n")
|
||||
for i, e := range t {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
}
|
||||
|
||||
// Create and send header.
|
||||
header := metadata.New(map[string]string{"location": "MTV", "timestamp": time.Now().Format(timestampFormat)})
|
||||
grpc.SendHeader(ctx, header)
|
||||
|
||||
fmt.Printf("request received: %v, sending echo\n", in)
|
||||
|
||||
return &pb.EchoResponse{Message: in.Message}, nil
|
||||
}
|
||||
|
||||
func (s *server) ServerStreamingEcho(in *pb.EchoRequest, stream pb.Echo_ServerStreamingEchoServer) error {
|
||||
fmt.Printf("--- ServerStreamingEcho ---\n")
|
||||
// Create trailer in defer to record function return time.
|
||||
defer func() {
|
||||
trailer := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
|
||||
stream.SetTrailer(trailer)
|
||||
}()
|
||||
|
||||
// Read metadata from client.
|
||||
md, ok := metadata.FromIncomingContext(stream.Context())
|
||||
if !ok {
|
||||
return status.Errorf(codes.DataLoss, "ServerStreamingEcho: failed to get metadata")
|
||||
}
|
||||
if t, ok := md["timestamp"]; ok {
|
||||
fmt.Printf("timestamp from metadata:\n")
|
||||
for i, e := range t {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
}
|
||||
|
||||
// Create and send header.
|
||||
header := metadata.New(map[string]string{"location": "MTV", "timestamp": time.Now().Format(timestampFormat)})
|
||||
stream.SendHeader(header)
|
||||
|
||||
fmt.Printf("request received: %v\n", in)
|
||||
|
||||
// Read requests and send responses.
|
||||
for i := 0; i < streamingCount; i++ {
|
||||
fmt.Printf("echo message %v\n", in.Message)
|
||||
err := stream.Send(&pb.EchoResponse{Message: in.Message})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *server) ClientStreamingEcho(stream pb.Echo_ClientStreamingEchoServer) error {
|
||||
fmt.Printf("--- ClientStreamingEcho ---\n")
|
||||
// Create trailer in defer to record function return time.
|
||||
defer func() {
|
||||
trailer := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
|
||||
stream.SetTrailer(trailer)
|
||||
}()
|
||||
|
||||
// Read metadata from client.
|
||||
md, ok := metadata.FromIncomingContext(stream.Context())
|
||||
if !ok {
|
||||
return status.Errorf(codes.DataLoss, "ClientStreamingEcho: failed to get metadata")
|
||||
}
|
||||
if t, ok := md["timestamp"]; ok {
|
||||
fmt.Printf("timestamp from metadata:\n")
|
||||
for i, e := range t {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
}
|
||||
|
||||
// Create and send header.
|
||||
header := metadata.New(map[string]string{"location": "MTV", "timestamp": time.Now().Format(timestampFormat)})
|
||||
stream.SendHeader(header)
|
||||
|
||||
// Read requests and send responses.
|
||||
var message string
|
||||
for {
|
||||
in, err := stream.Recv()
|
||||
if err == io.EOF {
|
||||
fmt.Printf("echo last received message\n")
|
||||
return stream.SendAndClose(&pb.EchoResponse{Message: message})
|
||||
}
|
||||
message = in.Message
|
||||
fmt.Printf("request received: %v, building echo\n", in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) BidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error {
|
||||
fmt.Printf("--- BidirectionalStreamingEcho ---\n")
|
||||
// Create trailer in defer to record function return time.
|
||||
defer func() {
|
||||
trailer := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
|
||||
stream.SetTrailer(trailer)
|
||||
}()
|
||||
|
||||
// Read metadata from client.
|
||||
md, ok := metadata.FromIncomingContext(stream.Context())
|
||||
if !ok {
|
||||
return status.Errorf(codes.DataLoss, "BidirectionalStreamingEcho: failed to get metadata")
|
||||
}
|
||||
|
||||
if t, ok := md["timestamp"]; ok {
|
||||
fmt.Printf("timestamp from metadata:\n")
|
||||
for i, e := range t {
|
||||
fmt.Printf(" %d. %s\n", i, e)
|
||||
}
|
||||
}
|
||||
|
||||
// Create and send header.
|
||||
header := metadata.New(map[string]string{"location": "MTV", "timestamp": time.Now().Format(timestampFormat)})
|
||||
stream.SendHeader(header)
|
||||
|
||||
// Read requests and send responses.
|
||||
for {
|
||||
in, err := stream.Recv()
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("request received %v, sending echo\n", in)
|
||||
if err := stream.Send(&pb.EchoResponse{Message: in.Message}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
|
||||
if err != nil {
|
||||
log.Fatalf("failed to listen: %v", err)
|
||||
}
|
||||
fmt.Printf("server listening at %v\n", lis.Addr())
|
||||
|
||||
s := grpc.NewServer()
|
||||
pb.RegisterEchoServer(s, &server{})
|
||||
s.Serve(lis)
|
||||
}
|
Reference in New Issue
Block a user