Search code examples
javaspringgateway

Spring Cloud Gateway 2.0 forward path variable


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


Solution

  • 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}