Home > Net >  How to prevent springboot gateway to forward to last element in the chain
How to prevent springboot gateway to forward to last element in the chain

Time:11-30

I am using springboot gateway for load balancing requests between my microservice

spring:
  application:
    name: gateway-service  
  cloud:
    gateway:
      routes:
      - id: baeldung
        uri: question.com/questions/444/ask
      - id: myOtherRouting
        uri:  answer.com/answers/333/answer

my problem is, if i send a wrong request like "question.com/questions/dasldkjasdas" then the request is forwarded to answer.com/answers/333/answer since this is the last chain in my config, how can i prevent this, and send notfound statuscode as response. I used

filters:
            - SetStatus=NOT_FOUND

https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.0.RELEASE/reference/html/#setstatus-gatewayfilter-factory

but this is not the best approuch i think.

CodePudding user response:

You don't have any predicate specified for your route definitions - which means both of them match any incoming request. From Spring Cloud Gateway:

Clients make requests to Spring Cloud Gateway. If the Gateway Handler Mapping determines that a request matches a Route, it is sent to the Gateway Web Handler.

and

Route: Route the basic building block of the gateway. It is defined by an ID, a destination URI, a collection of predicates and a collection of filters. A route is matched if aggregate predicate is true.

Since you don't have any predicate specified - your route matches the incoming request and the last one is winning.

  • Related