From e5334c7d57cc8a5e28f8cf4b7b2d15685b7a0194 Mon Sep 17 00:00:00 2001 From: EddeCCC Date: Mon, 13 May 2024 15:48:39 +0200 Subject: [PATCH] add method to inject eum-host dynamically from ENV variable --- .../petclinic/api/ApiGatewayApplication.java | 24 ++++++++++++++++++- .../src/main/resources/static/index.html | 16 +++++++------ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/ApiGatewayApplication.java b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/ApiGatewayApplication.java index df86a6fc2..b5716ee35 100644 --- a/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/ApiGatewayApplication.java +++ b/spring-petclinic-api-gateway/src/main/java/org/springframework/samples/petclinic/api/ApiGatewayApplication.java @@ -36,6 +36,8 @@ import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; +import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.time.Duration; @@ -65,6 +67,9 @@ public WebClient.Builder loadBalancedWebClientBuilder() { @Value("classpath:/static/index.html") private Resource indexHtml; + @Value("${EUM_HOST:localhost}") + private String eumHost; + /** * workaround solution for forwarding to index.html * @see #9785 @@ -73,10 +78,27 @@ public WebClient.Builder loadBalancedWebClientBuilder() { RouterFunction routerFunction() { RouterFunction router = RouterFunctions.resources("/**", new ClassPathResource("static/")) .andRoute(RequestPredicates.GET("/"), - request -> ServerResponse.ok().contentType(MediaType.TEXT_HTML).bodyValue(indexHtml)); + request -> ServerResponse.ok().contentType(MediaType.TEXT_HTML) + .bodyValue(injectDynamicEumHost()) + ); return router; } + /** + * workaround solution to use dynamic hosts for EUM instead of just localhost + * @return content of index.html with injected EUM-Host + */ + private String injectDynamicEumHost() { + try { + String indexHtmlContent = new String(indexHtml.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + + // Replace the placeholder with the actual host value + return indexHtmlContent.replace("${EUM_HOST}", eumHost); + } catch (IOException e) { + throw new RuntimeException("Could not read index.html"); + } + } + /** * Default Resilience4j circuit breaker configuration */ diff --git a/spring-petclinic-api-gateway/src/main/resources/static/index.html b/spring-petclinic-api-gateway/src/main/resources/static/index.html index 1cc2a872d..5fd8ee65e 100644 --- a/spring-petclinic-api-gateway/src/main/resources/static/index.html +++ b/spring-petclinic-api-gateway/src/main/resources/static/index.html @@ -50,15 +50,17 @@ - - - - - - + + + + + + + +