Gerardo Roza
Gerardo Roza

Reputation: 3394

Setting a header on a Spring Weblux ServerResponse based on reactive content

Spring 5's ServerResponse.HeadersBuilder provides a header(String, String) method to add a header to the response in a reactive stack (using the Functional Programming Model).

The problem is that my header dependends on the content that I want to retrieve, something like:

public Mono<ServerResponse> getEntity(ServerRequest request) {
    String entityId = request.pathVariable("id");
    Mono<MyEntity> entity = service.findEntity(entityId);
    String headerValue = "???" // The header value depends on the values of the entity, which is not present at this point, here I only have access to the Mono 
    return ok().header("my-header", headerValue)
        .contentType(MediaType.APPLICATION_JSON)
        .body(entity , MyEntity.class);
  }

How can I specify a 'reactive' header?

Upvotes: 0

Views: 1176

Answers (1)

Toerktumlare
Toerktumlare

Reputation: 14783

By mapping out what you want the application to do

return service.findEntity(entityId).flatMap(entity -> {
    // Check entity and extract header the way you want

    return ok().header( ... );   
});

Upvotes: 2

Related Questions