2016-10-13

Scala Request Uri Combinator Parser

URI Combinator Parser

In my last blog I created a URL parser but the HttpServletRequest is providing only path and query with the method getRequestUri() so I made a request URI parser too.

Code

This code needs the URL parser, see below.
import scala.util.parsing.combinator.RegexParsers
case class RequestUriTokens(path : Option[String], query : Option[String])
/**
* Useful parser when using HttpServletRequest.getRequestUri()
*
* @see javax.servlet.http.HttpServletRequest.getRequestUri()
*/
class RequestUriParser extends RegexParsers {
private val requestUriParser = someRequest
val notQuestionmark = """[^\?]*""".r
val any = """.*""".r
def someRequest = "/" ~> opt(notQuestionmark) ~ opt("?" ~> any) ^^ {
case path ~ query => new RequestUriTokens(path, query)
}
def applyOnUri(uri : String) = parseAll(requestUriParser, uri) match {
case Success(result, _) => Right(result)
case Failure(failure, _) => Left(failure)
case Error(error, _) => Left(error)
}
}
object RequestUriParser {
lazy val requestUriParser = new RequestUriParser
def apply(uri : String) = requestUriParser.applyOnUri(uri)
}

See

Link to the URL parser:
https://gist.github.com/AIMMOTH/b9903387cdf6b9377e9a7f6ca8887281

Inga kommentarer:

Skicka en kommentar