spring-cloud / spring-cloud-config

External configuration (server and client) for Spring Cloud
Apache License 2.0
1.96k stars 1.29k forks source link

URI is not changed even using GATEWAY_REQUEST_URL_ATTR #2599

Open DAVIAMERICO242 opened 2 weeks ago

DAVIAMERICO242 commented 2 weeks ago

Describe the bug I need to redirect URI port based on some repository, the repository works well, and it's not the problem, the problem is the default uri http://localhost:9998 is always being fallen in, even if portaBackend is not null and differente from 9998, I tried so many ways and it's still getting the wrong door

Sample

@Configuration
public class Balancer {

    @Autowired
    private AssinanteRepository assinanteRepository;

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("dynamic_route", r -> r.path("/**")
                                .filters(f -> f.filter((exchange, chain) -> {
                                    // GETTING 'CNPJ' FROM COOKIE/HEADER TO MATCH PORT IN REPOSITORY
                                    String cnpj;
                                    HttpCookie cnpjCookie = exchange.getRequest().getCookies().getFirst("cnpj");
                                    if (cnpjCookie != null) { 
                                        cnpj = cnpjCookie.getValue();
                                    } else { // Quando o usuário loga
                                        cnpj = exchange.getRequest().getHeaders().getFirst("cnpj");
                                    }

                                    // LOOKS FOR REGARDING PORT ON REPOSITORY BASED ON CNPJ
                                    Integer portaBackend = assinanteRepository.findById(cnpj)
                                            .map(assinante -> assinante.getApiPORT()).orElse(null);

                                    // MODIFIES THE REQUEST WHEN A PORT IS FOUND
                                    if (portaBackend != null) {
                                        // SET NEW URI
                                        String redirect = "http://localhost:" + portaBackend + exchange.getRequest().getURI().getPath();
                                        URI uri;
                                        try {
                                            uri = new URI(redirect);
                                        } catch (URISyntaxException e) {
                                            return Mono.error(new RuntimeException("Erro na construção da URI"));
                                        }

                                        // ADDING TO CONTEXT
                                        addOriginalRequestUrl(exchange, exchange.getRequest().getURI());

                                        // CHANGING URI REQUEST
                                        ServerHttpRequest modifiedRequest = exchange.getRequest().mutate().uri(uri).build();
                                        ServerWebExchange modifiedExchange = exchange.mutate().request(modifiedRequest).build();

                                        // CHANGING ATTRIBUTE
                                        modifiedExchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri);

                                        return chain.filter(modifiedExchange).then(Mono.fromRunnable(() -> {
                                            ServerHttpResponse response = exchange.getResponse();
                                            System.out.println("Requisição redirecionada para: " + redirect);
                                        }));
                                    } else {
                                        return Mono.error(new RuntimeException("CNPJ não encontrado"));
                                    }
                                })).uri("http://localhost:9998")
                        // 
                ).build();
    }
}
DAVIAMERICO242 commented 2 weeks ago

Solved using:

@Configuration
public class Balancer {

    @Autowired
    private AssinanteRepository assinanteRepository;

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("dynamic_route", r -> r.path("/**")
                                .filters(f ->{
                                    // GETTING 'CNPJ' FROM COOKIE/HEADER TO MATCH PORT IN REPOSITORY
                                    f.changeRequestUri(e -> {
                                        HttpCookie cnpjCookie = e.getRequest().getCookies().getFirst("cnpj");
                                        String cnpj;
                                        if(cnpjCookie!=null){
                                            cnpj = cnpjCookie.getValue();
                                        }else{
                                            cnpj = e.getRequest().getHeaders().getFirst("cnpj");
                                        }
                                        Integer port = assinanteRepository.findById(cnpj).get().getApiPORT();
                                        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUri(e.getRequest().getURI());
                                        String modifiedUri = uriBuilder.scheme("http").host("localhost").port(port).toUriString();
                                        return Optional.of(URI.create(modifiedUri));
                                    });
                                    return f;
                                }).uri("http://localhost:9998")
                                ).build();
                        //
    }
}