Adam Szabo
Adam Szabo

Reputation: 41

Spring cloud gateway routing with path

I'm trying to write a gateway routing with a path (route everything to www.example.com/foobar/), but the '/foobar/' part is ignored, and everything is routed to www.example.com/)

My RouteLocator configuration is:

@Bean
public RouteLocator myRouteLocator(final RouteLocatorBuilder builder) {
    return builder.routes()
            .route(route -> route.path("/**").uri("http://www.example.com/foobar"))
            .build();
}

When I call the service with http://localhost:8080/myApiCall, cloud gateway forwards the call to http://www.example.com/myApiCall instead of http://www.example.com/foobar/myApiCall.

If I call my service as http://localhost:8080/foobar/myApiCall, the resulting call is http://www.example.com/foobar/myApiCall, so it works correctly in this case.

Based on some debugging, my final URL is created here: https://github.com/spring-cloud/spring-cloud-gateway/blob/v3.1.3/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/RouteToRequestUrlFilter.java#L88 Where only the host is used, the path is omitted from the configuration.

My used versions: spring-cloud-gateway: v3.1.3 spring-core: v5.3.20

I have thought about just using a rewritepath filter to always append the /foobar/ part - but isn't there a better way?

Upvotes: 0

Views: 1986

Answers (1)

Sander Cobbaert
Sander Cobbaert

Reputation: 133

This can be achieved using the setPath Filter:

Configuring it using YAML:

spring:
  cloud:
    gateway:
      routes:
      - id: setpath_route
        uri: http://www.example.com
        predicates:
        - Path=/**
        filters:
        - SetPath=/foobar

Spring Cloud Gateway MVC: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-mvc/filters/setpath.html

Spring Cloud Gateway Reactive: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway/gatewayfilter-factories/setpath-factory.html

Upvotes: 0

Related Questions