akka-grpc
akka-grpc copied to clipboard
Add examples on how to add default metadata to `GrpcClientSettings`
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, 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 Thanks!
What is the import for GRPCMetadata I don't see any documentation for this and my IDE can't find it.
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.