### take Parser Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/zepto.md Example of using the take parser. ```Haskell take 4 -- Gets next 4 bytes ``` -------------------------------- ### Basic GET Request Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A simple GET request to the root of a website. ```http GET / HTTP/1.1 Host: www.reddit.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive ``` -------------------------------- ### string Parser Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/zepto.md Example of using the string parser. ```Haskell string "HTTP/" >> take 3 -- Match "HTTP/" then 3 bytes ``` -------------------------------- ### parse Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/errors.md An example demonstrating how to use `parse` and handle its `IResult`. ```haskell case parse myParser input of Done remainder result -> putStrLn $ "Success: " ++ show result Fail _ ctxs msg -> putStrLn $ "Error at: " ++ show ctxs ++ ": " ++ msg Partial k -> -- feed k moreInput ``` -------------------------------- ### anyChar Parser Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/text-parsing.md Example of using anyChar. ```Haskell anyChar -- Matches "X", returns 'X' ``` -------------------------------- ### parse Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/zepto.md Example usage of the parse function. ```Haskell import Data.Attoparsec.Zepto import qualified Data.ByteString as BS result = parse (string "GET" >> take 3) (BS.pack "GET /index") -- Right " /i" ``` -------------------------------- ### Sample HTTP Request Source: https://github.com/haskell/attoparsec/blob/master/benchmarks/http-request.txt An example of an HTTP GET request with various headers, suitable for benchmarking. ```http GET / HTTP/1.1 Host: twitter.com Accept: text/html, application/xhtml+xml, application/xml; q=0.9, image/webp, */*; q=0.8 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-GB,en-US;q=0.8,en;q=0.6 Cache-Control: max-age=0 Cookie: guest_id=v1%3A139; _twitter_sess=BAh7CSIKZmxhc2hJQz-e1e1; __utma=43838368.452555194.1399611824.1; __utmb=43838368; __utmc=43838368; __utmz=1399611824.1.1.utmcsr=(direct)|utmcmd=(none) User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.86 Safari/537.36 ``` -------------------------------- ### Example HTTP Request 10 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for an image. ```http GET /hVMVTDdjuY3bQox5.jpg HTTP/1.1 Host: f.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Example HTTP Request 5 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for an image. ```http GET /ixd1C1njpczEWC22.jpg HTTP/1.1 Host: c.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Example HTTP Request 7 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for an image. ```http GET /zT4yQmDxQLbIxK1b.jpg HTTP/1.1 Host: c.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Example HTTP Request 12 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for an image. ```http GET /gZJL1jNylKbGV4d-.jpg HTTP/1.1 Host: d.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Alternative Usage Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/zepto.md Example of using the Alternative instance for choice. ```Haskell method = string "GET" <|> string "POST" <|> string "PUT" ``` -------------------------------- ### Example HTTP Request 2 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt Another sample HTTP GET request for an image, with similar headers. ```http GET /S-IpsJrOKuaK9GZ8.jpg HTTP/1.1 Host: c.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Example HTTP Request 13 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for an image. ```http GET /aNd2zNRLXiMnKUFh.jpg HTTP/1.1 Host: c.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### GET Request for Favicon Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A GET request for the favicon. ```http GET /favicon.ico HTTP/1.1 Host: www.redditstatic.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive ``` -------------------------------- ### Example HTTP Request 11 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for an image. ```http GET /rnWf8CjBcyPQs5y_.jpg HTTP/1.1 Host: f.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Example HTTP Request 15 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for a PNG file. ```http GET /sprite-reddit.an0Lnf61Ap4.png HTTP/1.1 Host: www.redditstatic.com ``` -------------------------------- ### Example HTTP Request 1 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for an image, including headers. ```http Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ GET /eMWMpmm9APNeNqcF.jpg HTTP/1.1 Host: e.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### atEnd Parser Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/zepto.md Example of using the atEnd parser. ```Haskell string "END" >> atEnd -- Match END at end ``` -------------------------------- ### Testing Patterns Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/usage-examples.md Demonstrates how to test Attoparsec parsers using QuickCheck for property-based and roundtrip testing, and provides an example for performance testing. ```haskell import Test.QuickCheck import Test.Hspec -- Property-based testing spec = describe "Parser" $ do it "parses positive integers" $ parseOnly decimal "123" `shouldBe` Right (123 :: Int) it "fails on empty input" $ isLeft (parseOnly decimal "") it "leaves non-digits" $ parseOnly decimal "123abc" `shouldBe` Right (123 :: Int) -- Roundtrip testing prop_roundtrip x = parseOnly parser (serialize x) == Right x -- Performance testing bench :: Int -> IO () bench n = do let input = BS.replicate n '1' let start = getCPUTime parseOnly (many digit) input let elapsed = getCPUTime - start putStrLn $ "Parsed " ++ show n ++ " digits in " ++ show elapsed ++ "ms" ``` -------------------------------- ### Example HTTP Request 3 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for an image. ```http GET /3V6dj9PDsNnheDXn.jpg HTTP/1.1 Host: c.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Dropbox Notification Request Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt An example of an HTTP GET request for Dropbox notifications. ```http GET /subscribe?host_int=1042356184&ns_map=571794054_374233948806,464381511_13349283399&user_id=245722467&nid=1399334269710011966&ts=1400862514 HTTP/1.1 Host: notify8.dropbox.com Accept-Encoding: identity Connection: keep-alive X-Dropbox-Locale: en_US User-Agent: DropboxDesktopClient/2.7.54 (Macintosh; 10.8; ('i32',); en_US) ``` -------------------------------- ### Adzerk Advertiser Image Request (ads-load.html referer) Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt Example HTTP GET request to static.adzerk.net for an advertiser image, with a different referer. ```http GET /Advertisers/63cfd0044ffd49c0a71a6626f7a1d8f0.jpg HTTP/1.1 Host: static.adzerk.net User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://static.adzerk.net/reddit/ads-load.html?bust2 ``` -------------------------------- ### Example HTTP Request 6 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for an image. ```http GET /nGsQj15VyOHMwmq8.jpg HTTP/1.1 Host: c.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Example HTTP Request 9 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for an image. ```http GET /WJFFPxD8X4JO_lIG.jpg HTTP/1.1 Host: f.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Adzerk Advertiser Image Request Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt Example HTTP GET request to static.adzerk.net for an advertiser image. ```http GET /Advertisers/a774d7d6148046efa89403a8db635a81.jpg HTTP/1.1 Host: static.adzerk.net User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://static.adzerk.net/reddit/ads.html?sr=-reddit.com&bust2 ``` -------------------------------- ### GET Request for Image File Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A GET request for an image file, including a Referer header. ```http GET /kill.png HTTP/1.1 Host: www.redditstatic.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Example HTTP Request 8 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for an image. ```http GET /L5e1HcZLv1iu4nrG.jpg HTTP/1.1 Host: f.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Adzerk Static Asset Requests Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt Example HTTP GET requests to static.adzrk.net for JavaScript and CSS files. ```http GET /Extensions/adFeedback.js HTTP/1.1 Host: static.adzrk.net User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: */* Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://static.adzerk.net/reddit/ads.html?sr=-reddit.com&bust2 ``` ```http GET /Extensions/adFeedback.css HTTP/1.1 Host: static.adzrk.net User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: text/css,*/*;q=0.1 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://static.adzerk.net/reddit/ads.html?sr=-reddit.com&bust2 ``` -------------------------------- ### Parsing Configuration Files Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/usage-examples.md Parses a simple key-value configuration file format, ignoring comments and blank lines. ```haskell #{-# LANGUAGE OverloadedStrings #-} import Data.Attoparsec.Text import qualified Data.Text as T import qualified Data.Text.IO as TIO import Data.Map (Map) import qualified Data.Map as Map type Config = Map String String -- Configuration file format: key = value configLine = do skipSpace key <- takeWhile1 (/= '=') skipSpace char '=' skipSpace value <- takeTill (\c -> c == '\n') skipSpace return (T.unpack key, T.unpack value) -- Skip comments and blank lines comment = skipSpace *> char '#' *> manyTill anyChar endOfLine *> pure () blank = skipSpace *> endOfLine *> pure () -- Configuration file configFile = do skipSpace items <- many (try comment <|> try blank <|> configLine) return $ Map.fromList items -- Usage loadConfig :: FilePath -> IO (Either String Config) loadConfig path = do content <- TIO.readFile path return $ parseOnly configFile content -- Example config file: -- # Comment -- debug = true -- port = 8080 -- host = localhost ``` -------------------------------- ### takeWhile Parser Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/zepto.md Example of using the takeWhile parser. ```Haskell takeWhile (\w -> w /= 10) -- Until newline ``` -------------------------------- ### eitherResult Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/errors.md An example demonstrating the use of `eitherResult`. ```haskell case eitherResult (parse myParser input) of Right val -> processValue val Left err -> handleError err ``` -------------------------------- ### Example HTTP Request 4 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for an image. ```http GET /wQ3-VmNXhv8sg4SJ.jpg HTTP/1.1 Host: c.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### GET Request for CSS File Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A GET request for a CSS file, including a Referer header. ```http GET /reddit.v_EZwRzV-Ns.css HTTP/1.1 Host: www.redditstatic.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: text/css,*/*;q=0.1 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Reddit Ad Request Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt An example of an HTTP GET request for an ad from Reddit. ```http User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://static.adzerk.net/reddit/ads-load.html?bust2 Cookie: S_9994987=6754579095859875029; A4=01fmFvgRnI09SF00000; u2=d1263d39-874b-4a89-86cd-a2ab0860ed4e3Zl040 GET /i.gif?e=eyJhdiI6NjIzNTcsImF0Ijo4LCJjbSI6MTE2MzUxLCJjaCI6Nzk4NCwiY3IiOjMzNzAxOCwiZGkiOiI3OTdlZjU3OWQ5NjE0ODdiODYyMGMyMGJkOTE4YzNiMSIsImRtIjoxLCJmYyI6NDE2MTMxLCJmbCI6MjEwNDY0LCJrdyI6Ii1yZWRkaXQuY29tIiwibWsiOiItcmVkZGl0LmNvbSIsIm53Ijo1MTQ2LCJwYyI6MCwicHIiOjIwMzYyLCJydCI6MSwicmYiOiJodHRwOi8vd3d3LnJlZGRpdC5jb20vIiwic3QiOjI0OTUwLCJ1ayI6InVlMS01ZWIwOGFlZWQ5YTc0MDFjOTE5NWNiOTMzZWI3Yzk2NiIsInRzIjoxNDAwODYyNTkzNjRmfQ&s=OjzxzXAgQksbdQOHNm-bjZcnZPA HTTP/1.1 Host: engine.adzerk.net User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://static.adzerk.net/reddit/ads-load.html?bust2 Cookie: azk=ue1-5eb08aeed9a7401c9195cb933eb7c966 ``` -------------------------------- ### Parsing with State Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/usage-examples.md Shows how to incorporate state into parsers, such as tracking line and column numbers during parsing. This example uses IORef to manage mutable state within the parsing process. ```haskell {-# LANGUAGE OverloadedStrings #-} import Data.Attoparsec.Text import Data.IORef import Control.Monad (when) -- Parse with state tracking data ParserState = ParserState { lineNum :: Int , colNum :: Int } deriving Show -- Track position during parsing withState :: Parser a -> IO (Either String (a, ParserState)) withState parser = do stateRef <- newIORef (ParserState 1 1) let statefulParser = do let updateState c = do st <- readIORef stateRef let (line, col) = if c == '\n' then (lineNum st + 1, 1) else (lineNum st, colNum st + 1) writeIORef stateRef (ParserState line col) a <- parser st <- readIORef stateRef return (a, st) -- Parse and return with state return undefined -- Simplified example ``` -------------------------------- ### maybeResult Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/errors.md An example demonstrating the use of `maybeResult`. ```haskell maybeResult (parse myParser input) >>= print ``` -------------------------------- ### Monadic Composition Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/zepto.md Example of using monadic composition with Zepto. ```Haskell parser = do _ <- string "GET " path <- takeWhile (/= 32) _ <- string " HTTP/" version <- take 3 return (path, version) ``` -------------------------------- ### GET Request for CSS File on Subdomain Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A GET request for a CSS file hosted on a thumbs.redditmedia.com subdomain. ```http GET /rZ_rD5TjrJM0E9Aj.css HTTP/1.1 Host: e.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: text/css,*/*;q=0.1 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### string Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/bytestring-char8.md Example of using string to match a specific prefix. ```Haskell string "HTTP/" ``` -------------------------------- ### GET Request for JavaScript File Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A GET request for a JavaScript file, including a Referer header. ```http GET /reddit-init.en-us.O1zuMqOOQvY.js HTTP/1.1 Host: www.redditstatic.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: */* Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### parseT Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/zepto.md Example usage of the parseT function. ```Haskell result <- parseT myParser (BS.pack "data") case result of Right val -> print val Left err -> putStrLn err ``` -------------------------------- ### Running Parsers Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/quick-reference.md Examples of how to run Attoparsec parsers with strict ByteString, strict Text, lazy ByteString, and Zepto. ```Haskell -- Strict ByteString parse parser input -- IResult parseOnly parser input -- Either String parseTest parser input -- Print to stdout parseWith getInput parser initial -- Monadic refill -- Strict Text parse parser input -- IResult parseOnly parser input -- Either String -- Lazy parse parser lazyInput -- Result (no Partial) -- Zepto Zepto.parse parser input -- Either String ``` -------------------------------- ### HTTP Request Parsing Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/zepto.md An example demonstrating how to parse a simple HTTP request using Zepto. ```haskell import Data.Attoparsec.Zepto import qualified Data.ByteString as BS data HttpRequest = HttpRequest { method :: ByteString , path :: ByteString , version :: ByteString } deriving Show httpRequest :: Parser HttpRequest httpRequest = do m <- takeWhile (/= 32) -- Method until space _ <- string " " p <- takeWhile (/= 32) -- Path until space _ <- string " HTTP/" v <- take 3 -- Version "1.1" etc return (HttpRequest m p v) main = do let input = BS.pack "GET /index.html HTTP/1.1\r\n" case parse httpRequest input of Right req -> print req Left err -> putStrLn $ "Error: " ++ err ``` -------------------------------- ### Adzerk HTML Load Request Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt Example HTTP GET request to static.adzerk.net for an HTML ad loading page. ```http GET /reddit/ads-load.html?bust2 HTTP/1.1 Host: static.adzerk.net User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Serving-Sys BurstingPipe Request Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt Example HTTP GET request to bs.serving-sys.com for ad server bursting pipe, likely for impression tracking. ```http GET /BurstingPipe/adServer.bs?cn=tf&c=19&mc=imp&pli=9994987&PluID=0&ord=1400862593644&rtu=-1 HTTP/1.1 Host: bs.serving-sys.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://static.adzerk.net/reddit/ads.html?sr=-reddit.com&bust2 ``` ```http GET /BurstingPipe/adServer.bs?cn=tf&c=19&mc=imp&pli=9962555&PluID=0&ord=1400862593645&rtu=-1 HTTP/1.1 Host: bs.serving-sys.com ``` -------------------------------- ### GET Request for JPG Image Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A GET request for a JPG image hosted on a thumbs.redditmedia.com subdomain. ```http GET /AMZM4CWd6zstSC8y.jpg HTTP/1.1 Host: b.thumbs.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### Example HTTP Request 14 Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt A sample HTTP GET request for a GIF file. ```http GET /droparrowgray.gif HTTP/1.1 Host: www.redditstatic.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.redditstatic.com/reddit.v_EZwRzV-Ns.css ``` -------------------------------- ### Custom Parser Combinators Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/usage-examples.md Provides examples of custom parser combinators that can be built using Attoparsec's combinator library. This includes functions for counting items separated by a delimiter, left-associative chaining, and optional parsing with actions. ```haskell -- Parse exactly N items separated by separator countSepBy :: Int -> Parser a -> Parser s -> Parser [a] countSepBy n p sep = go 0 [] where go count acc | count >= n = return (reverse acc) | count == 0 = do a <- p go 1 (a:acc) | otherwise = do sep a <- p go (count + 1) (a:acc) -- Chainl1 for left-associative operators chainl1 :: Parser a -> Parser (a -> a -> a) -> Parser a chainl1 p op = do a <- p rest a where rest a = do o <- op b <- p rest (o a b) <|> return a -- Optional with action optionally :: Parser a -> (a -> Parser b) -> Parser (Maybe b) optionally p action = (Just <$> (p >>= action)) <|> return Nothing ``` -------------------------------- ### MonadIO Usage Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/zepto.md Example of performing I/O within a Zepto parser. ```Haskell parser = do n <- take 4 liftIO $ putStrLn ("Got " ++ show n) return n ``` -------------------------------- ### eitherP Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/bytestring-parsing.md Example usage of eitherP to parse either 'on' or 'off'. ```Haskell eitherP (string "on") (string "off") ``` -------------------------------- ### Incremental Parsing Example with feed Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/errors.md An example showing how to use `feed` for incremental parsing with a list of ByteStrings. ```haskell parseIncremental :: Parser a -> [ByteString] -> Either String a parseIncremental parser inputs = go (parse parser "") where go (Done _ a) = Right a go (Fail _ _ msg) = Left msg go (Partial k) = case inputs of [] -> go (feed (Partial k) "") -- Signal EOF (x:xs) -> go (feed (Partial k) x) ``` -------------------------------- ### parseOnly Function Examples Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/text-parsing.md Examples demonstrating the behavior of parseOnly. ```Haskell parseOnly letter "A" -- Right 'A' parseOnly digit "x" -- Left "not a digit" ``` -------------------------------- ### Parsing Log Files Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/usage-examples.md Parses log entries with timestamps, levels, and messages. ```haskell #{-# LANGUAGE OverloadedStrings #-} import Data.Attoparsec.ByteString.Char8 import qualified Data.ByteString as BS import Data.Time (UTCTime) import Data.Time.Format (parseTimeOrError, defaultTimeLocale) data LogEntry = LogEntry { timestamp :: String , level :: String , message :: String } deriving Show -- ISO 8601 timestamp timestamp = count 19 anyChar -- "2024-05-27T12:34:56" -- Log level logLevel = "DEBUG" <|> "INFO" <|> "WARN" <|> "ERROR" -- Log entry logEntry = do ts <- timestamp skipSpace char '[' lv <- logLevel char ']' skipSpace msg <- takeTill (\c -> c == '\n') endOfLine return LogEntry { timestamp = ts, level = lv, message = msg } -- Multiple entries logFile = many logEntry -- Usage parseLogFile :: FilePath -> IO (Either String [LogEntry]) parseLogFile path = do content <- BS.readFile path return $ parseOnly logFile content ``` -------------------------------- ### Incremental Parsing Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/usage-examples.md Demonstrates how to parse input incrementally, which is useful for handling large inputs or network streams. It shows a parser that works on chunks of ByteString and how to signal the end of input. ```haskell {-# LANGUAGE OverloadedStrings #-} import Data.Attoparsec.ByteString import qualified Data.ByteString as BS import Control.Monad (forever) -- Parser that works incrementally myParser = many (decimal :: Parser Int) <* endOfInput -- Feed input incrementally parseIncrementally :: Parser a -> [BS.ByteString] -> Either String a parseIncrementally parser chunks = go (parse parser "") where go (Done _ a) = Right a go (Fail _ ctx msg) = Left msg go (Partial k) = case chunks of [] -> go (feed (Partial k) "") -- Signal EOF (x:xs) -> go (feed (Partial k) x) -- Usage with network socket parseStream socket parser = go (parse parser "") where go (Done rest a) = return a go (Fail _ _ msg) = fail msg go (Partial k) = do chunk <- BS.hGetSome socket 4096 if BS.null chunk then go (feed (Partial k) "") -- EOF else go (feed (Partial k) chunk) ``` -------------------------------- ### Reddit Pixel Tracking Request Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt Example HTTP GET request to pixel.redditmedia.com for tracking pixel. ```http GET /pixel/of_doom.png?id=t3_25jzeq-t8_k2ii&hash=da31d967485cdbd459ce1e9a5dde279fef7fc381&r=1738649500 HTTP/1.1 Host: pixel.redditmedia.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://www.reddit.com/ ``` -------------------------------- ### match Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/bytestring-parsing.md Example usage of match to return consumed bytes and parse result. ```Haskell match (many1 digit) -- Returns ("123", [49,50,51]) ``` -------------------------------- ### Incremental Input Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/quick-reference.md An example of how to handle incremental parsing with Attoparsec. ```Haskell parseIncremental p input = go (parse p input) where go (Done rest a) = Right a go (Fail _ _ msg) = Left msg go (Partial k) = go (k "") -- Signal EOF ``` -------------------------------- ### Adzerk Engine Request Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt Example HTTP GET request to Adzerk's engine.adzerk.net for ad serving. ```http GET /ados?t=1400862512892&request={%22Placements%22:[{%22A%22:5146,%22S%22:24950,%22D%22:%22main%22,%22AT%22:5},{%22A%22:5146,%22S%22:24950,%22D%22:%22sponsorship%22,%22AT%22:8}],%22Keywords%22:%22-reddit.com%22,%22Referrer%22:%22http%3A%2F%2Fwww.reddit.com%2F%22,%22IsAsync%22:true,%22WriteResults%22:true} HTTP/1.1 Host: engine.adzerk.net User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: */* Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://static.adzerk.net/reddit/ads.html?sr=-reddit.com&bust2 ``` -------------------------------- ### parseOnly Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/errors.md An example demonstrating how to use `parseOnly` and handle its `Either` result. ```haskell case parseOnly decimal "123" of Right n -> print n Left err -> putStrLn $ "Parse error: " ++ err ``` -------------------------------- ### Adzerk Tracker Request Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt Example HTTP GET request to Adzerk's secure.adzerk.net for tracking information. ```http GET /fetch-trackers?callback=jQuery111005268222517967478_1400862512407&ids%5B%5D=t3_25jzeq-t8_k2ii&_=1400862512408 HTTP/1.1 Host: secure.adzerk.net User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: */* Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://static.adzerk.net/reddit/ads.html?sr=-reddit.com&bust2 ``` -------------------------------- ### Alternative Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/combinators.md Example of using the alternative operator (<|>) to try the next parser if the first fails. ```haskell -- Alternative: try next option digit <|> letter ``` -------------------------------- ### Adzerk Dynamic Image Request Source: https://github.com/haskell/attoparsec/blob/master/examples/http-requests.txt Example HTTP GET request to engine.adzerk.net for a dynamically generated image, likely for tracking or reporting. ```http GET /i.gif?e=eyJhdiI6NjIzNTcsImF0Ijo1LCJjbSI6MTE2MzUxLCJjaCI6Nzk4NCwiY3IiOjMzNzAxNSwiZGkiOiI4NmI2Y2UzYWM5NDM0MjhkOTk2ZTg4MjYwZDE5ZTE1YyIsImRtIjoxLCJmYyI6NDE2MTI4LCJmbCI6MjEwNDY0LCJrdyI6Ii1yZWRkaXQuY29tIiwibWsiOiItcmVkZGl0LmNvbSIsIm53Ijo1MTQ2LCJwYyI6MCwicHIiOjIwMzYyLCJydCI6MSwicmYiOiJodHRwOi8vd3d3LnJlZGRpdC5jb20vIiwic3QiOjI0OTUwLCJ1ayI6InVlMS01ZWIwOGFlZWQ5YTc0MDFjOTE5NWNiOTMzZWI3Yzk2NiIsInRzIjoxNDAwODYyNTkzNjQ1fQ&s=lwlbFf2Uywt7zVBFRj_qXXu7msY HTTP/1.1 Host: engine.adzerk.net User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: image/png,image/*;q=0.8,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://static.adzerk.net/reddit/ads.html?sr=-reddit.com&bust2 Cookie: azk=ue1-5eb08aeed9a7401c9195cb933eb7c966 ``` -------------------------------- ### Complete Input (Most Common) Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/quick-reference.md Example of parsing a complete ByteString input using `parseOnly`. ```Haskell import Data.Attoparsec.ByteString.Char8 case parseOnly myParser input of Right result -> process result Left err -> putStrLn err ``` -------------------------------- ### Building Error Messages Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/errors.md Illustrates how context stacks from inner to outer parsers when building error messages. ```haskell parser = (string "PREFIX" "prefix") *> (many digit "digits") <* (string "SUFFIX" "suffix") -- If fails on SUFFIX: -- Context: ["suffix", "digits", "prefix"] -- Formatted: "prefix > digits > suffix: string" ``` -------------------------------- ### Parsing HTTP Requests Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/usage-examples.md Parses a simplified HTTP request, including method, path, version, and headers. ```haskell #{-# LANGUAGE OverloadedStrings #-} import Data.Attoparsec.ByteString as P import Data.Attoparsec.ByteString.Char8 import qualified Data.ByteString as BS import Data.Word (Word8) data HttpRequest = HttpRequest { method :: BS.ByteString , path :: BS.ByteString , version :: BS.ByteString , headers :: [(BS.ByteString, BS.ByteString)] } deriving Show -- HTTP method httpMethod = string "GET" <|> string "POST" <|> string "PUT" <|> string "DELETE" -- HTTP version httpVersion = string "HTTP/" >> takeWhile (/= '\r') -- Request line requestLine = do m <- httpMethod skipSpace p <- takeWhile (\c -> c /= ' ') skipSpace v <- httpVersion endOfLine return (m, p, v) -- Header line headerLine = do name <- takeWhile (\c -> c /= ':') char ':' skipSpace value <- takeTill (\c -> c == '\r' || c == '\n') endOfLine return (name, value) -- Full request httpRequest = do (m, p, v) <- requestLine hs <- many headerLine endOfLine return HttpRequest { method = m, path = p, version = v, headers = hs } -- Usage main = do input <- BS.readFile "request.txt" case parseOnly httpRequest input of Right req -> print req Left err -> putStrLn $ "Parse error: " ++ err ``` -------------------------------- ### satisfy Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/bytestring-char8.md Example of using satisfy to match digits. ```Haskell satisfy isDigit -- Matches '0'-'9' ``` -------------------------------- ### satisfy Function Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/text-parsing.md Example of using satisfy with a predicate. ```Haskell satisfy isAlpha -- Matches letters ``` -------------------------------- ### skipMany Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/bytestring-parsing.md Example usage of skipMany to skip all whitespace characters. ```Haskell skipMany space -- Skip all spaces ``` -------------------------------- ### Apply Example Source: https://github.com/haskell/attoparsec/blob/master/_autodocs/api-reference/combinators.md Example of using the apply operator (<*>) for function application within parsers. ```haskell -- Apply: function application in parser (+) <$> decimal <*> (char '+' *> decimal) ```