语言代码应用作 Routes 实例的每个路由的前缀。路由有效,但反向路由不起作用:
应将当前HttpHeaders的语言代码作为前缀添加到从反向路由返回的每个 Call 中。实现此目标的最佳方法是什么?也许有一种方法可以自定义路线生成?
我目前正在研究的方法是使用自定义的 HttpRequestHandler 进行正确的路由。如果存在语言代码,则该处理程序将更新请求的路径和持久语言。
class RequestHandler @Inject()(
webCommands: WebCommands,
optionalDevContext: OptionalDevContext,
errorHandler: HttpErrorHandler,
configuration: HttpConfiguration,
filters: HttpFilters,
routes: router.Routes
) extends DefaultHttpRequestHandler(
webCommands,
optionalDevContext,
routes,
errorHandler,
configuration,
filters
) {
val langRouteRegex = "/(.{2})(/.*)?".r
override def routeRequest(request: RequestHeader): Option[Handler] = {
val updatedRequest = request.path match {
case langRouteRegex(lang, path) =>
updateLangRequest(request, lang, path)
case _ =>
request
}
super.routeRequest(updatedRequest)
}
def updateLangRequest(requestHeader: RequestHeader, lang: String, path: String): RequestHeader = {
requestHeader
.withTarget(requestHeader.target.withPath(if (path == null) "/" else path))
.withTransientLang(lang)
}
}