如何使用喷涂路由进行内部重定向

时间:2015-07-06 06:06:20

标签: scala redirect routing spray

我想用喷涂路线做类似的事情

如果服务器收到请求

  • http://myserver/a/1然后回复内容

  • http://myserver/a/2然后临时重定向到http://myserver/b; 但是因为这是内部重定向而不是发送 重定向到客户端,让客户端进行另一个http get调用new 网址;宁可选择做内部重定向

  • http://myserver/b然后回复内容

以下是我提出的计划;我希望得到其他人对此的评论,如果我可以通过在代码中删除2个 routeB 的引用来改进它

class RedirectTestService(val actorRefFactory: ActorRefFactory) extends HttpService {

  //For troubleshooting purpose only 
  val extractURI = extract { ctx =>
    ctx.request.uri
  }

  def mapRequestContextWithPath(pathStr: String) = mapRequestContext(_.copy(unmatchedPath = Path(pathStr)))

  val routeB = extractURI { uri =>
    println("For troubleshooting" + uri)
    pathPrefix("b") {
      get {
        complete {
          "got a B"
        }
      }
    }
  }
  val routeA = pathPrefix("a" / IntNumber) { id =>
    get {
      if (id == 1)
        complete {
          "got an A with id = " + id
        }
      else {
        mapRequestContextWithPath("/b") {
          routeB
        }
      }
    }
  }
  val route = routeA ~ routeB
}

// this trait defines our service behavior independently from the service actor
trait TestService extends HttpService {
  val myRoute = // new LongerService(actorRefFactory).route
    new RedirectTestService(actorRefFactory).route
}

@RunWith(classOf[JUnitRunner])
class RedirectTestServiceTest extends Specification with Specs2RouteTest with TestService {
  def actorRefFactory = system

  "RedirectTestService" should {
    "return response" in {
      Get("/a/1") ~> myRoute ~> check {
        responseAs[String] === "got an A with id = 1"
      }

      Get("/b") ~> myRoute ~> check {
        responseAs[String] === "got a B"
      }

      Get("/a/2") ~> myRoute ~> check {
        responseAs[String] === "got a B"
      }
    }
  }
}

0 个答案:

没有答案