Skip to content

Instantly share code, notes, and snippets.

@m-renaud
Last active August 29, 2015 14:10
Show Gist options
  • Save m-renaud/a8f1169e36f53acc57c3 to your computer and use it in GitHub Desktop.
Save m-renaud/a8f1169e36f53acc57c3 to your computer and use it in GitHub Desktop.
Parse the query component of a URI.
module ParseUriQuery where
import Control.Applicative
import Data.Attoparsec.ByteString.Char8
import Data.ByteString.Char8 (ByteString, pack, unpack)
import Data.Either
data QueryTerm = QueryTerm { termName :: ByteString
, termValue :: Maybe ByteString
} deriving (Eq, Read, Show)
termList = queryTerm `sepBy` (char '&')
queryTerm = QueryTerm <$> name <*> value
name = takeWhile1 notTermSeparator <* discardEqualsSign
where notTermSeparator = notInClass "&="
discardEqualsSign = option '=' (char '=')
value = option Nothing nonEmptyValue
where nonEmptyValue = Just <$> takeWhile1 (/= '&')
-- Convenience function.
runParser :: Parser c -> String -> c
runParser p = head . rights . return . parseOnly p . pack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment