akka-grpc icon indicating copy to clipboard operation
akka-grpc copied to clipboard

Add examples on how to add default metadata to `GrpcClientSettings`

Open benthecarman opened this issue 4 years ago • 3 comments

In the docs it states that you can add default metadata to GrpcClientSettings, however there are no example on even how to add something like the .addHeader("key", "value") that is shown for the individual request.

benthecarman avatar Mar 29 '21 12:03 benthecarman

@benthecarman, I've no idea if this is the recommended way of doing it, but it might help you. Here's an example of adding a bearer token to the Authorisation header.

import akka.grpc.GrpcClientSettings
import io.grpc.{CallCredentials, Metadata}

import java.util.concurrent.Executor

val token = "my_token"
val clientSettings = GrpcClientSettings
  .connectToServiceAt("127.0.0.1", port)
  .withCallCredentials(new CallCredentials {
    def applyRequestMetadata(
      requestInfo: CallCredentials.RequestInfo, appExecutor: Executor, applier: CallCredentials.MetadataApplier
    ): Unit = {
      appExecutor.execute(() => {
        val metadata = new Metadata();
        val key = Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER)
        val value = s"Bearer $token"
        metadata.put(key, value)
        applier.apply(metadata);
      });
    }

    def thisUsesUnstableApi(): Unit = ()
  })

So just use metadata.put to add the headers you need.

(Updated to remove renaming import)

davidcorcoran avatar Apr 27 '21 13:04 davidcorcoran

@davidcorcoran Thanks!

What is the import for GRPCMetadata I don't see any documentation for this and my IDE can't find it.

benthecarman avatar Apr 27 '21 16:04 benthecarman

GRPCMetadata

@benthecarman

Ah sorry. That's just io.grpc.Metadata. I have a class called Metadata and it was clashing. So my import was import io.grpc.{Metadata => GRPCMetadata}

I'll fix my example.

davidcorcoran avatar Apr 29 '21 15:04 davidcorcoran