SetRequestHeader Filter

SetRequestHeader 过滤器采用 namevalue 参数。以下清单配置了一个 SetRequestHeader 过滤器:

application.yml
spring:
  cloud:
    gateway:
      mvc:
        routes:
        - id: setrequestheader_route
          uri: https://example.org
          filters:
          - SetRequestHeader=X-Request-Red, Blue
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.setRequestHostHeader;
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> gatewayRouterFunctionsSetRequestHeader() {
		return route("add_request_parameter_route")
				.GET("/**", http("https://example.org"))
					.before(setRequestHostHeader("X-Request-Red", "Blue"))
					.build();
    }
}

此过滤器替换(而不是添加)所有具有给定名称的标头。因此,如果下游服务器响应 X-Request-Red:1234,它将被替换为 X-Request-Red:Blue,这是下游服务将接收到的内容。

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

application.yml
spring:
  cloud:
    gateway:
      routes:
      - id: setrequestheader_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - SetRequestHeader=X-Request-Red, Blue-{segment}
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.setRequestHostHeader;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;
import static import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.host;

@Configuration
class RouteConfiguration {

    @Bean
    public RouterFunction<ServerResponse> gatewayRouterFunctionsSetRequestHeader() {
		return route("add_request_parameter_route")
				.route(host("{segment}.myhost.org"), http("https://example.org"))
					.before(setRequestHostHeader("X-Request-Red", "Blue-{segment}"))
					.build();
    }
}