1 回答
TA贡献1810条经验 获得超4个赞
您可以使用 ServerHttpRequest 作为方法参数来获取 :uri
@RestController
public class GreetingController {
@GetMapping("/greeting")
public Mono<Greeting> getGreeting(ServerHttpRequest serverHttpRequest) {
return Mono.just(new Greeting("greeting", serverHttpRequest.getURI().toString()));
}
}
如果运行在负载均衡器后面,最好应了解标头。linkToCurrentResourceX-Forwarded-???
然后,您可以公开转发标题变压器。@Bean
从其文档中:
从 “” 和 “” 标头中提取值以覆盖请求(即 ),以便它反映客户端发起的协议和地址。ForwardedX-Forwarded-*URIHttpRequest.getURI()
@Configuration
open class MvcConfig {
@Bean
open fun forwardedHeaderTransformer() = ForwardedHeaderTransformer()
}
以下是一些测试:
@ExtendWith(SpringExtension::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
properties = ["server.port=4333"])
class GreetingController2Test {
@Autowired
private lateinit var restTemplate: TestRestTemplate
@Test
fun `should return uri`() {
val responseEntity = restTemplate.getForEntity("/greeting", Greeting::class.java)
val greeting = responseEntity.body!!
assertEquals("http://localhost:4333/greeting", greeting.uri)
}
@Test
fun `should return uri composed from forwarded-??? headers`() {
val headers = HttpHeaders()
headers["X-Forwarded-Host"] = "external-uri.com"
headers["X-Forwarded-Proto"] = "https"
headers["X-Forwarded-Prefix"] = "/prefix"
val httpEntity = HttpEntity(null, headers)
val responseEntity = restTemplate.exchange("/greeting", HttpMethod.GET, httpEntity, Greeting::class.java)
val greeting = responseEntity.body!!
assertEquals("https://external-uri.com/prefix/greeting", greeting.uri)
}
}
和 :Greeting.kt
data class Greeting(
val g: String? = null,
val uri: String? = null
)
添加回答
举报