Skip to content

Commit

Permalink
Allows adding literal header values to RequestTemplate
Browse files Browse the repository at this point in the history
This change adds a new method RequestTemplate#headerLiteral which allows adding headers which are not interpreted as Template expressions. This allows adding empty JSON objects to headers in RequestInterceptor implementations.

Fixes OpenFeign#2252, OpenFeign#1987
  • Loading branch information
dvag-yannick-reifschneider committed Jul 10, 2024
1 parent 4b01b6b commit e0ef292
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
30 changes: 30 additions & 0 deletions core/src/main/java/feign/RequestTemplate.java
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,36 @@ public RequestTemplate header(String name, Iterable<String> values) {
return appendHeader(name, values);
}

/**
* @see RequestTemplate#headerLiteral(String, Iterable)
*/
public RequestTemplate headerLiteral(String name, String... values) {
if (values == null) {
return appendHeader(name, Collections.emptyList(), true);
}

return headerLiteral(name, Arrays.asList(values));
}

/**
* Specify a Header, with the specified values. Values are treated as literals. Template
* expressions are not resolved.
*
* @param name of the header.
* @param values for this header.
* @return a RequestTemplate for chaining.
*/
public RequestTemplate headerLiteral(String name, Iterable<String> values) {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("name is required.");
}
if (values == null) {
values = Collections.emptyList();
}

return appendHeader(name, values, true);
}

/**
* Clear on reader from {@link RequestTemplate}
*
Expand Down
20 changes: 20 additions & 0 deletions core/src/test/java/feign/RequestTemplateTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,26 @@ void resolveTemplateWithHeaderEmptyResult() {
assertThat(template).hasNoHeader("Encoded");
}

@Test
void templateWithEmptyJsonObjectLiteralHeader() {
String emptyJsonObject = "{}";
RequestTemplate template =
new RequestTemplate().method(HttpMethod.GET).headerLiteral("A-Header", emptyJsonObject);

template.resolve(new LinkedHashMap<>());
assertThat(template).hasHeaders(entry("A-Header", Collections.singletonList(emptyJsonObject)));
}

@Test
void templateWithTemplateExpressionLiteralHeader() {
String header = "{var}";
RequestTemplate template =
new RequestTemplate().method(HttpMethod.GET).headerLiteral("A-Header", header);

template = template.resolve(mapOf("var", "value"));
assertThat(template).hasHeaders(entry("A-Header", Collections.singletonList(header)));
}

@Test
void resolveTemplateWithMixedRequestLineParams() {
RequestTemplate template = new RequestTemplate().method(HttpMethod.GET)//
Expand Down

0 comments on commit e0ef292

Please sign in to comment.