如何在 Liftweb 中进行通用重写?

How do to a generic rewrite in Liftweb?

我想以通用方式重写 url。例如,我在 CSV 文件中有一个 url 列表,读取它们并想在 Liftweb.

中重写 URL

例如该文件包含

buy-electronics/products/:id

cheap-phones/products/:id

我想将它们重写为

/products?id=[id from path]

我只在 Liftweb 中找到了大小写匹配的示例。通过大小写匹配,它看起来像:

case RewriteRequest(
  ParsePath("buy-electronics" :: "products" :: id :: Nil), _, _, _), _, _) => {
        RewriteResponse(
          List("products"), Map("id" -> id)
        )
  }

但我没有找到任何关于如何以通用方式添加重写规则的信息。除了生成 Scala 代码之外还有什么想法吗?

您可以使用模式匹配守卫来实现这一点。

在一个简化的例子中,假设路径的第一部分(购买电子产品、廉价手机)是唯一真正改变的东西(也许这甚至对你的情况有用),你可以添加一个守卫检查它是否包含在您从 CSV 文件中读取的列表中。

// actually read from CSV
val prefixes = Seq("buy-electronics", "cheap-phones")

case RewriteRequest(ParsePath(prefix :: "products" :: id :: Nil), _, _, _), _, _)
  if (prefixes contains prefix) => 
    RewriteResponse(List("products"), Map("id" -> id))

如果您需要更复杂的结构成为可能,您可以将整个路径绑定到一个变量中 (... ParsePath(path), _, ...) 并检查该值是否与列表中的某些行匹配,再次在 guard 表达式中.