From ef81f2c3102a2036dfc9a20777556f5e0b20c33e Mon Sep 17 00:00:00 2001 From: Pedro Ivo AC <36969819+ImPedro29@users.noreply.github.com> Date: Thu, 13 Jun 2024 07:16:12 -0300 Subject: [PATCH] change to a generic authentication example (#42) * change to a generic authentication example * Update examples/authentication/main.go Co-authored-by: Anush --------- Co-authored-by: Bastian Hofmann Co-authored-by: Anush --- examples/authentication/main.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/examples/authentication/main.go b/examples/authentication/main.go index a5bb6a2..b927492 100644 --- a/examples/authentication/main.go +++ b/examples/authentication/main.go @@ -22,7 +22,7 @@ func main() { flag.Parse() // Set up a connection to the server. config := &tls.Config{} - conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(credentials.NewTLS(config))) + conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(credentials.NewTLS(config)), grpc.WithUnaryInterceptor(interceptor)) if err != nil { log.Fatalf("did not connect: %v", err) } @@ -32,8 +32,6 @@ func main() { // Contact the server and print out its response. ctx, cancel := context.WithTimeout(context.Background(), time.Second) - md := metadata.New(map[string]string{"api-key": "secret-key-*******"}) - ctx = metadata.NewOutgoingContext(ctx, md) defer cancel() r, err := collections_client.List(ctx, &pb.ListCollectionsRequest{}) if err != nil { @@ -41,3 +39,8 @@ func main() { } log.Printf("List of collections: %s", r.GetCollections()) } + +func interceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + newCtx := metadata.AppendToOutgoingContext(ctx, "api-key", "secret-key-*******") + return invoker(newCtx, method, req, reply, cc, opts...) +}