I'm developing a system in a microservices architecture using java8 and Spring Cloud. I implemented a post rest controller that receives an object in json and then saves it in the database. The problem is; how do I get the URI containing the API Gateway of the just saved object so I can return it on the created responde body?
Like, when I use
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedProfile.getId()).toUri();
I get http://Boss.mshome.net:8081/profile/1
instead of localhost:8765/nukr-profile-service/profile/1
which is the endpoint with the API Gateway's path.
What's the best practice to retrieve this URI?
So, I came to a solution I just don't know if it's best practice or not. My post method ended up being like:
@PostMapping("/profile")
public ResponseEntity<Object> createProfile(@Valid @RequestBody Profile profile) {
UriComponents requestComponents = ServletUriComponentsBuilder.fromCurrentRequest().path("").build();
InstanceInfo gatewayService = this.eurekaClient.getNextServerFromEureka(NUKR_API_GATEWAY_SERVICE, false);
Profile savedProfile = this.profileRepository.save(profile);
String uriStr = requestComponents.getScheme() + "://" + gatewayService.getIPAddr() + ":" + gatewayService.getPort() + "/" + this.profileServiceName +
requestComponents.getPath() + "/" + savedProfile.getId();
return ResponseEntity.created(URI.create(uriStr)).build();
}