Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

URI is not changed even using GATEWAY_REQUEST_URL_ATTR #2599

Open
DAVIAMERICO242 opened this issue Oct 21, 2024 · 1 comment
Open

URI is not changed even using GATEWAY_REQUEST_URL_ATTR #2599

DAVIAMERICO242 opened this issue Oct 21, 2024 · 1 comment

Comments

@DAVIAMERICO242
Copy link

DAVIAMERICO242 commented Oct 21, 2024

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
Copy link
Author

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();
                        //
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant