RequestContext custom attributes

When you are using multiple decorators, you might want to pass some value to the next decorator. You can do this by attaching attributes to a RequestContext. To attach an attribute, you need to define an AttributeKey first:

import io.netty.util.AttributeKey;

public final class MyAttributeKeys {
    public static final AttributeKey<Integer> INT_ATTR =
            AttributeKey.valueOf(MyAttributeKeys.class, "INT_ATTR");
    public static final AttributeKey<MyBean> BEAN_ATTR =
            AttributeKey.valueOf(MyAttributeKeys.class, "BEAN_ATTR");

Then, you can access them via RequestContext.attr():

// Setting
ctx.setAttr(INT_ATTR, 42);
MyBean myBean = new MyBean();
ctx.setAttr(BEAN_ATTR, new MyBean());

// Getting
Integer i = ctx.attr(INT_ATTR); // i == 42
MyBean bean = ctx.attr(BEAN_ATTR); // bean == myBean

You can also iterate over all the attributes in a context using RequestContext.attrs():

ctx.attrs().forEachRemaining(e -> {
    System.err.println(e.getKey() + ": " + e.getValue());

Setting attributes using WebClientRequestPreparation

You can set attributes when building a request using WebClient.prepare().

import com.linecorp.armeria.client.WebClient;

static final AttributeKey<Integer> USER_ID = AttributeKey.valueOf(MyAttributeKeys.class, "USER_ID");
static final AttributeKey<String> USER_SECRET = AttributeKey.valueOf(MyAttributeKeys.class, "USER_SECRET");

WebClient client = WebClient.of("");
      .attr(USER_ID, userId)
      .attr(USER_SECRET, secret)

Setting attributes using RequestOptions

You can also create a RequestOptions and pass it to WebClient.execute(HttpRequest,RequestOptions) with an HttpRequest.

import com.linecorp.armeria.client.RequestOptions;
import com.linecorp.armeria.common.HttpRequest;

HttpRequest req = HttpRequest.of(HttpMethod.GET, "/my-service");
RequestOptions options = RequestOptions.builder()
                                       .attr(USER_ID, userId)
                                       .attr(USER_SECRET, secret)
client.execute(req, options);