-
Notifications
You must be signed in to change notification settings - Fork 3.4k
add AddResponseHeadersIfNotPresentGatewayFilterFactory #3756
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JoeCqupt
wants to merge
4
commits into
spring-cloud:main
Choose a base branch
from
JoeCqupt:feat1
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
...ver-webflux/gatewayfilter-factories/addresponseheadersifnotpresent-factory.adoc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
[[addresponseheadersifnotpresent-gatewayfilter-factory]] | ||
= `AddResponseHeadersIfNotPresent` `GatewayFilter` Factory | ||
|
||
The `AddResponseHeadersIfNotPresent` `GatewayFilter` factory takes a collection of `name` and `value` pairs separated by colon. | ||
The following example configures an `AddResponseHeadersIfNotPresent` `GatewayFilter`: | ||
|
||
.application.yml | ||
[source,yaml] | ||
---- | ||
spring: | ||
cloud: | ||
gateway: | ||
routes: | ||
- id: add_response_headers_if_not_present_route | ||
uri: https://example.org | ||
filters: | ||
- AddResponseHeadersIfNotPresent=X-Response-Color-1:blue,X-Response-Color-2:green | ||
---- | ||
|
||
|
||
This listing adds 2 headers `X-Response-Color-1:blue` and `X-Response-Color-2:green` to the downstream response's headers for all matching requests. | ||
This is similar to how `AddResponseHeader` works, but unlike `AddResponseHeader` it will do it only if the header is not already there. | ||
Otherwise, the original value in the response is return. | ||
|
||
Additionally, to set a multi-valued header, use the header name multiple times like `AddResponseHeadersIfNotPresent=X-Response-Color-1:blue,X-Response-Color-1:green`. | ||
|
||
`AddResponseHeadersIfNotPresent` also supports URI variables used to match a path or host. | ||
URI variables may be used in the value and are expanded at runtime. | ||
The following example configures an `AddResponseHeadersIfNotPresent` `GatewayFilter` that uses a variable: | ||
|
||
.application.yml | ||
[source,yaml] | ||
---- | ||
spring: | ||
cloud: | ||
gateway: | ||
routes: | ||
- id: add_response_headers_if_not_present_route | ||
uri: https://example.org | ||
predicates: | ||
- Path=/red/{segment} | ||
filters: | ||
- AddResponseHeadersIfNotPresent=X-Response-Red:Blue-{segment} | ||
---- |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
124 changes: 124 additions & 0 deletions
124
...work/cloud/gateway/filter/factory/AddResponseHeadersIfNotPresentGatewayFilterFactory.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
/* | ||
* Copyright 2013-2025 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.springframework.cloud.gateway.filter.factory; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Collections; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.stream.Collectors; | ||
|
||
import reactor.core.publisher.Mono; | ||
|
||
import org.springframework.cloud.gateway.filter.GatewayFilter; | ||
import org.springframework.cloud.gateway.filter.GatewayFilterChain; | ||
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils; | ||
import org.springframework.cloud.gateway.support.config.KeyValue; | ||
import org.springframework.cloud.gateway.support.config.KeyValueConfig; | ||
import org.springframework.core.style.ToStringCreator; | ||
import org.springframework.http.HttpHeaders; | ||
import org.springframework.util.StringUtils; | ||
import org.springframework.web.server.ServerWebExchange; | ||
|
||
import static org.springframework.cloud.gateway.support.GatewayToStringStyler.filterToStringCreator; | ||
|
||
/** | ||
* Adds one or more headers to the response’s headers without overriding previous values. | ||
* If the header is are already present, value(s) will not be set. | ||
* | ||
* @author jiangyuan | ||
*/ | ||
public class AddResponseHeadersIfNotPresentGatewayFilterFactory extends AbstractGatewayFilterFactory<KeyValueConfig> { | ||
|
||
@Override | ||
public GatewayFilter apply(KeyValueConfig config) { | ||
return new GatewayFilter() { | ||
@Override | ||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { | ||
return chain.filter(exchange) | ||
.then(Mono.fromRunnable(() -> addResponseHeaderIfNotPresent(exchange, config))); | ||
} | ||
|
||
@Override | ||
public String toString() { | ||
ToStringCreator toStringCreator = filterToStringCreator( | ||
AddResponseHeadersIfNotPresentGatewayFilterFactory.this); | ||
for (KeyValue keyValue : config.getKeyValues()) { | ||
toStringCreator.append(keyValue.getKey(), keyValue.getValue()); | ||
} | ||
return toStringCreator.toString(); | ||
} | ||
}; | ||
} | ||
|
||
private void addResponseHeaderIfNotPresent(ServerWebExchange exchange, KeyValueConfig config) { | ||
if (!exchange.getResponse().isCommitted()) { | ||
Map<String, List<String>> aggregatedHeaders = new HashMap<>(); | ||
for (KeyValue keyValue : config.getKeyValues()) { | ||
String key = keyValue.getKey(); | ||
List<String> candidateValue = aggregatedHeaders.get(key); | ||
if (candidateValue == null) { | ||
candidateValue = new ArrayList<>(); | ||
candidateValue.add(keyValue.getValue()); | ||
aggregatedHeaders.put(key, candidateValue); | ||
} | ||
else { | ||
candidateValue.add(keyValue.getValue()); | ||
} | ||
} | ||
|
||
HttpHeaders headers = exchange.getResponse().getHeaders(); | ||
for (Map.Entry<String, List<String>> kv : aggregatedHeaders.entrySet()) { | ||
String headerName = kv.getKey(); | ||
|
||
boolean headerIsMissingOrBlank = headers.getOrEmpty(headerName) | ||
.stream() | ||
.allMatch(h -> !StringUtils.hasText(h)); | ||
|
||
if (headerIsMissingOrBlank) { | ||
List<String> replacedValues = kv.getValue() | ||
.stream() | ||
.map(value -> ServerWebExchangeUtils.expand(exchange, value)) | ||
.collect(Collectors.toList()); | ||
headers.addAll(headerName, replacedValues); | ||
} | ||
} | ||
} | ||
} | ||
|
||
@Override | ||
public ShortcutType shortcutType() { | ||
return ShortcutType.GATHER_LIST; | ||
} | ||
|
||
@Override | ||
public List<String> shortcutFieldOrder() { | ||
return Collections.singletonList("keyValues"); | ||
} | ||
|
||
@Override | ||
public KeyValueConfig newConfig() { | ||
return new KeyValueConfig(); | ||
} | ||
|
||
@Override | ||
public Class<KeyValueConfig> getConfigClass() { | ||
return KeyValueConfig.class; | ||
} | ||
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wouldn't it be useful to also add the option to override the header if it is present? The default could be to do nothing if the header is there but we could add a configuration option to allow the override behavior
cc: @spencergibb