How to forward a path variable in Spring Cloud Gateway 2.0?
If we have an microservice that has 2 endpoints: /users
and /users/{id}
and is running on port 8080, how to forward the request to the endpoint with the id path variable?
The following gateway configuration successfully forwards to the /users
end point, but the second route forwards the request to the same /users
endpoint of the real service.
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("users", t -> t.path("/users").uri("http://localhost:8080/users"))
.route("userById", t -> t.path("/users/**").uri("http://localhost:8080/users/"))
.build();
}
I'm using spring-cloud-starter-gateway
from spring cloud Finchley.BUILD-SNAPSHOT
Spring Cloud Gateway. This project provides an API Gateway built on top of the Spring Ecosystem, including: Spring 5, Spring Boot 2 and Project Reactor. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency.
Route Predicate Factories Spring Cloud Gateway matches routes as part of the Spring WebFlux HandlerMappinginfrastructure. Spring Cloud Gateway includes many built-in route predicate factories. All of these predicates match on different attributes of the HTTP request. You can combine multiple route predicate factories with logical andstatements.
The SetPathGatewayFilterfactory takes a path templateparameter. It offers a simple way to manipulate the request path by allowing templated segments of the path. This uses the URI templates from Spring Framework. Multiple matching segments are allowed. The following example configures a SetPathGatewayFilter: Example 41. application.yml
In this example, there is no fallbackendpoint or handler in the gateway application. However, there is one in another application, registered under localhost:9994. In case of the request being forwarded to fallback, the Spring Cloud CircuitBreaker Gateway filter also provides the Throwablethat has caused it.
A rewritePath
filter has to be used:
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("users", t -> t.path("/users")
.uri("http://localhost:8080/users"))
.route("userById", t -> t.path("/users/**")
.filters(rw -> rw.rewritePath("/users/(?<segment>.*)", "/users/${segment}"))
.uri("http://localhost:8080/users/"))
.build();
}
The YAML version is specified in the documentation:
spring:
cloud:
gateway:
routes:
- id: rewritepath_route
uri: http://example.org
predicates:
- Path=/foo/**
filters:
- RewritePath=/foo/(?<segment>.*), /$\{segment}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With