【发布时间】:2021-03-23 17:31:40
【问题描述】:
我正在使用 Spring 的 Functional Endpoints 和 Kotlin 来创建 Web 服务,并且我正在尝试找出使用标准 Accept-Language 标头解决 Locale 关闭的惯用方法。
下面是代码的示例:
val repository: PersonRepository = ...
val handler = PersonHandler(repository)
val route = coRouter {
GET("/person", handler::getPeople)
}
class PersonHandler(private val repository: PersonRepository) {
suspend fun getPeople(request: ServerRequest): ServerResponse {
val locale = /* ??? */
// create and return response
}
}
Spring 文档引用使用 LocaleContextResolver 将 Locale 作为请求的一部分进行解析,但在使用功能端点时我看不到使用它的方法。您可以像这样从ServiceRequest.headers().acceptLanguage() 获取传递到Accept-Language 标头的原始 值...
suspend fun getPeople(request: ServerRequest): ServerResponse {
val locale =
Locale.lookup(request.headers().acceptLanguage(), supportedLocales)
?: Locale.getDefault()
// create and return response
}
.. 但这不是在每个 Handler Function 中重新实现LocaleContextResolver 的职责吗?
在 Spring 的功能端点中将 Accept-Language 标头转换为单个/最受支持的 Locale 的惯用方法是什么?
【问题讨论】:
标签: spring spring-boot kotlin