Scala模式与varargs匹配

时间:2019-05-09 17:00:54

标签: scala

我有一个Web服务器来处理传入的请求。基于http方法和端点,我处理请求的方式有所不同。当前代码可以处理它:

<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-3133XXXX-X');
</script>

The code I am using for each button is:

<div class="get-ticket-btn"> <a href="<?php echo get_post_meta($landing_page->ID, "landing_tickets_url", true);?>" onClick="ga('send', 'event', 'Button Click', 'Get Ticket click', 'Get Tickets Now');" class="btn">Get Tickets Now !</a> </div>

<button type="submit" onClick="ga('send', 'event', 'Button Click', 'Get Coupon click', 'Get My Coupon');" class="btn btn-default">GET MY COUPON</button>

<a href="<?php echo get_post_meta($landing_page->ID, "landing_tickets_url", true);?>" onClick="ga('send', 'event', 'Button Click', 'Get Ticket click', 'Get Tickets Now');" class="btn">Get Tickets Now !</a> </div>

但是现在我需要支持许多这种形式的相关端点:

def routes: HttpRequest => Future[HttpResponse] = { httpRequest: HttpRequest =>
    (httpRequest.method, httpRequest.uri.path.toString) match {
      case (GET, "/login") =>
         process(getLogin)

      case (POST, "/newUser") =>
        process(createNewUser)   

      ..

例如:

/{version}/{serviceName}

所以我想更新现有代码以支持新端点:

/0/userService
/0/bookService

我该怎么做?

2 个答案:

答案 0 :(得分:3)

您可以执行以下操作:

val UrlPattern: scala.util.matching.Regex = """/(.*)/(.*)""".r
val path = "/0/userService"  

path match {
    case UrlPattern(version, service) => println(version, version)
}

上面的代码将导致:

(0, userService)

被打印到控制台,但是您可以随心所欲使用变量。

答案 1 :(得分:1)

您可以做类似

的操作
val v0Services = (s: String) => s.toLowerCase match {
    case "userservice" => userServiceV0()
    case "bookservice" => bookServiceV0()
}
val v1Services = (s: String) => s.toLowerCase match {
    case "userservice" => userServiceV1()
    case "bookservice" => bookServiceV1()
}
val check = (v: String) => v match {
    case "0" => v0Services
    case "1" => v1Services
}



case (POST, "/${version}/${service}) => check(version)(service)