可以代理现有路由的默认路由

时间:2014-06-10 23:39:16

标签: playframework routing

假设我有以下路线:

GET   /blog/:blogName          controllers.blog.show(blogName: String)
GET   /blog/:blogName/:postId  controllers.blog.getPost(blogName: String, postId: Int)

所以这适用于URLS,如:

www.example.com/blog/corporate
www.example.com/blog/corporate/1231

目标是使用标准路由,但我想以某种方式支持以下内容。 假设我想要一个名为' corporate'的博客的自定义网址。在这个URL工作:

   corporate.example.com
   corporate.example.com/12321

由于行动只是功能,我希望我能够以某种方式创造一个“全能”#34;然后将该请求简单地代理到现有路由,例如。

示例,网址:corporate.example.com/12321我想要这样做:

def catchAll(): Action = {

   val blogName = request...  // extract the subdomain "corporate"
   val postId = // ... extract postId from the URL

   controller.blog.getPost(blogName, postId)
}

注意:我可能有100个这样的博客,所以我无法将其编码到路线中。这个想法是我想知道我是否可以通过"代理"以某种方式重新使用现有路线。在我自己手动过滤掉网址中的部分后,请求不匹配到正确路线的路线。

1 个答案:

答案 0 :(得分:3)

你也许可以定义这样的路线:

# These two routes can do the "proxying"
GET    /                controllers.blog.view
GET    /:postId         controllers.blog.catchAll(postId: Int)

# These can be your fallback routes
GET   /blog/:blogName           controllers.blog.show(blogName: String)
GET   /blog/:blogName/:postId   controllers.blog.getPost(blogName: String, postId: Int)

然后在博客控制器中,您的“代理”功能:

def view = Action.async { request =>
     // request.host = "subdomain.example.com" in your example, though it may be wiser to try a more sophisticated function with  a regex to handle the extraction.
    val subdomain: String = request.host.split('.').head
    show(subdomain)(request)
}

def catchAll(postId: Int) = Action.async { request =>
    val subdomain: String = request.host.split('.').head
    getPost(subdomain, postId)(request)
}

由于控制器函数showgetPost返回Action,当应用的是函数Request => Future[Result]时,我们只将原始请求传递给Action.apply }。

请注意,由于Action.apply返回Future,我需要更改viewcatchAll以使用Action.async来处理Future[Result]

相关问题