I'm writing Scala/Play 2.0 application, and I want my code to return different page depending on request. Here is my code:
// Validate client and return temporary credentials
def requestToken = Action { request =>
// Authorization header may present or not
val authHeader = parseHeaders(request headers AUTHORIZATION)
// Authorization header may contain such keys or not
val clientKey = authHeader("oauth_consumer_key")
val signature = authHeader("oauth_signature")
if (authenticateClient(clientKey, signature)) {
...
Ok(...)
} else {
Unauthorized(...)
}
}
The problem arise when request is malformed and some headers are missing, then NoSuchElementException is thrown.
In imperative language, I would validate every step like this:
if (!request.headers.contains(AUTHORIZATION))
return Unathorized
val authHeader = parseHeaders(request headers AUTHORIZATION)
if (!authHeader.contains("oauth_consumer_key") || !authHeader.contains("oauth_signature"))
return Unathorized
val clientKey = authHeader("oauth_consumer_key")
val signature = authHeader("oauth_signature")
...
but what should I do to solve such problem in a functional way?
You can use authHeader.get(key)
which returns an Option[B]. Your code then would look something like this:
val result = for {
auth <- request.headers.get(AUTHORIZATION)
authHeader = parseHeaders(auth)
clientKey <- authHeader.get("oauth_consumer_key")
signature <- authHeader.get("oauth_signature")
} yield { ... }
result.getOrElse(Unauthorized)
Explanation:
The whole expression will only be executed, if there is no None
value. So if all headers are present you will get a result
of Some[A]
and if one or more are absent, you will get None
. result.getOrElse(Unauthorized)
will return the contained value for Some[A]
and Unauthorized
for None
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With