AddResponseHeader Filter

AddResponseHeader 过滤器采用一个 namevalue 参数。以下示例配置一个 AddResponseHeader 过滤器:

application.yml
spring:
  cloud:
    gateway:
      mvc:
        routes:
        - id: add_response_header_route
          uri: https://example.org
          filters:
          - AddResponseHeader=X-Response-Red, Blue
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.AfterFilterFunctions.addResponseHeader;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;

@Configuration
class RouteConfiguration {

    @Bean
    public RouterFunction<ServerResponse> gatewayRouterFunctionsAddRespHeader() {
        return route("addresponseheader")
                .GET("/anything/addresheader", http("https://example.org"))
                .after(addResponseHeader("X-Response-Red", "Blue"))
            .build();
    }
}

这将为所有匹配请求将 X-Response-Red:Blue 标头添加到下游响应标头。

AddResponseHeader 了解用于匹配路径或主机的 URI 变量。URI 变量可以用于该值并在运行时展开。以下示例配置一个使用变量的 AddResponseHeader 过滤器:

GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.AfterFilterFunctions.addResponseHeader;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;
import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.host;

@Configuration
class RouteConfiguration {

    @Bean
    public RouterFunction<ServerResponse> gatewayRouterFunctionsAddRespHeader() {
		return route("add_response_header_route")
				.route(host("{segment}.myhost.org"), http("https://example.org"))
				.after(addResponseHeader("foo", "bar-{segment}"))
				.build();
    }
}