我是Akka HTTP的新手,我想知道如何从Akka HTTP请求中提取cookie。如果可能,有人可以发布一个如何使用Scala完成此操作的示例吗?
答案 0 :(得分:2)
正如documentation所述,您可以使用cookie
指令从请求中提取Cookie:
val route = cookie("userName") { nameCookie => complete(s"The logged in user is '${nameCookie.value}'") } // tests: Get("/") ~> Cookie("userName" -> "paul") ~> route ~> check { responseAs[String] shouldEqual "The logged in user is 'paul'" } // missing cookie Get("/") ~> route ~> check { rejection shouldEqual MissingCookieRejection("userName") } Get("/") ~> Route.seal(route) ~> check { responseAs[String] shouldEqual "Request is missing required cookie 'userName'" }
还有optionalCookie
指令:
val route = optionalCookie("userName") { case Some(nameCookie) => complete(s"The logged in user is '${nameCookie.value}'") case None => complete("No user logged in") } // tests: Get("/") ~> Cookie("userName" -> "paul") ~> route ~> check { responseAs[String] shouldEqual "The logged in user is 'paul'" } Get("/") ~> route ~> check { responseAs[String] shouldEqual "No user logged in" }