Skip to content

Instantly share code, notes, and snippets.

@salrashid123
Last active January 12, 2021 13:43
Show Gist options
  • Save salrashid123/a26e5d5bec4a5522f4dde8bcbaeb0e80 to your computer and use it in GitHub Desktop.
Save salrashid123/a26e5d5bec4a5522f4dde8bcbaeb0e80 to your computer and use it in GitHub Desktop.
RequestReason with perRPC
package main
import (
"context"
"flag"
"fmt"
"os"
"cloud.google.com/go/pubsub"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
var (
projectID = flag.String("project", "", "Project ID")
)
type clientMetadataKey string
func main() {
flag.Parse()
if *projectID == "" {
fmt.Fprintln(os.Stderr, "missing -project flag")
flag.Usage()
os.Exit(2)
}
// https://cloud.google.com/service-infrastructure/docs/service-control/reference/rpc/google.rpc/context#request
ctx := context.Background()
client, err := pubsub.NewClient(ctx, *projectID, option.WithGRPCDialOption(grpc.WithUnaryInterceptor(func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
c := ctx.Value(clientMetadataKey("reason")).(string)
send, _ := metadata.FromOutgoingContext(ctx)
send.Set("X-Goog-Request-Reason", c)
ctx = metadata.NewOutgoingContext(ctx, send)
err := invoker(ctx, method, req, reply, cc, opts...)
return err
})))
if err != nil {
fmt.Errorf("Could not create pubsub Client: %v", err)
return
}
newCtx := context.WithValue(ctx, clientMetadataKey("reason"), "foo")
topics := client.Topics(newCtx)
for {
topic, err := topics.Next()
if err == iterator.Done {
break
}
if err != nil {
fmt.Errorf("Error listing topics %v", err)
return
}
fmt.Println(topic)
}
newCtx = context.WithValue(ctx, clientMetadataKey("reason"), "bar")
topics = client.Topics(newCtx)
for {
topic, err := topics.Next()
if err == iterator.Done {
break
}
if err != nil {
fmt.Errorf("Error listing topics %v", err)
return
}
fmt.Println(topic)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment