optionalCookie
Description
Extracts an optional cookie with a given name from a request.
Use the cookie directive instead if the inner route does not handle a missing cookie.
Example
- Scala
-
source
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" }
- Java
-
source
import static org.apache.pekko.http.javadsl.server.Directives.complete; import static org.apache.pekko.http.javadsl.server.Directives.optionalCookie; final Route route = optionalCookie( "userName", optNameCookie -> { if (optNameCookie.isPresent()) { return complete("The logged in user is '" + optNameCookie.get().value() + "'"); } else { return complete("No user logged in"); } }); // tests: testRoute(route) .run(HttpRequest.GET("/").addHeader(Cookie.create("userName", "paul"))) .assertEntity("The logged in user is 'paul'"); testRoute(route).run(HttpRequest.GET("/")).assertEntity("No user logged in");
1.0.1