!_3      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                                   ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~                                                                                                                                   !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~&None%None2C happstack-server!Specify the lifetime of a cookie.|Note that we always set the max-age and expires headers because internet explorer does not honor max-age. You can specific  or Z and the other will be calculated for you. Choose which ever one makes your life easiest.happstack-server/session cookie - expires when browser is closedhappstack-serverlife time of cookie in secondshappstack-servercookie expiration datehappstack-servercookie already expiredhappstack-server/a type for HTTP cookies. Usually created using .happstack-serverqCreates a cookie with a default version of 1, empty domain, a path of "/", secure == False and httpOnly == False see also:  addCookiehappstack-serverSet a Cookie in the Result. The values are escaped as per RFC 2109, but some browsers may have buggy support for cookies containing e.g. '"' or ' '.Also, it seems that chrome, safari, and other webkit browsers do not like cookies which have double quotes around the domain and reject/ignore the cookie. So, we no longer quote the domain.[internet explorer does not honor the max-age directive so we set both max-age and expires.See  and J for a convenient way of calculating the first argument to this function.happstack-serveruNot an supported api. Takes a cookie header and returns either a String error message or an array of parsed cookieshappstack-server3not a supported api. A parser for RFC 2109 cookieshappstack-serverGet all cookies from the HTTP request. The cookies are ordered per RFC from the most specific to the least specific. Multiple cookies with the same name are allowed to exist.happstack-serverGet the most specific cookie with the given name. Fails if there is no such cookie or if the browser did not escape cookies in a proper fashion. Browser support for escaping cookies properly is very diverse.happstack-server cookie namehappstack-server cookie value    SafeDSafeWhappstack-serverBFormat the time as describe in the Apache combined log format. 3http://httpd.apache.org/docs/2.2/logs.html#combinedThe format is: [daymonthyear:hour:minute:second zone] day = 2*digit month = 3*letter year = 4*digit hour = 2*digit minute = 2*digit second = 2*digit zone = ( |  ) 4*digit happstack-serverEFormat the request as describe in the Apache combined log format. 3http://httpd.apache.org/docs/2.2/logs.html#combinedThe format is: "%h - %u %t "%r" %>s %b "%{Referer}i" "%{User-agent}i"" %h: This is the IP address of the client (remote host) which made the request to the server. %u: This is the userid of the person requesting the document as determined by HTTP authentication. %t: The time that the request was received. %r: The request line from the client is given in double quotes. %>s: This is the status code that the server sends back to the client. %b: The last part indicates the size of the object returned to the client, not including the response headers. %{Referer}: The RefererO (sic) HTTP request header. %{User-agent}: The User-Agent HTTP request header.  i(c) Peter Thiemann 2001,2002 (c) Bjorn Bringert 2005-2006 (c) Lemmih 2007 BSD-style lemmih@vo.com experimentalportableSafek %happstack-server A MIME media type value. The + instance is derived automatically. Use .9 to obtain the standard string representation. See  #http://www.ietf.org/rfc/rfc2046.txt0 for more information about MIME media types.'happstack-serverThe top-level media type, the general type of the data. Common examples are "text", "image", "audio", "video", "multipart", and "application".(happstack-servernThe media subtype, the specific data format. Examples include "plain", "html", "jpeg", "form-data", etc.)happstack-serverlMedia type parameters. On common example is the charset parameter for the "text" top-level type, e.g. ("charset","ISO-8859-1")..happstack-serverfProduce the standard string representation of a content-type, e.g. "text/html; charset=ISO-8859-1"./happstack-servernParse the standard representation of a content-type. If the input cannot be parsed, this function calls . with a (hopefully) informative error message.happstack-serverRFC 822 LWSP-charhappstack-server"RFC 822 CRLF (but more permissive)happstack-serverOne line!"#$%&'()*+,-./012345*-+,%&'()0/.#$21!"435NonelNonephappstack-server:Converts a HostAddress to a String in dot-decimal notationhappstack-server5Converts a IPv6 HostAddress6 to standard hex notationBhappstack-serverDalternative implementation of accept to work around EAI_AGAIN errorsBCBCSaferxEhappstack-serverA timeout managerNhappstack-server!terminate all threads immediately DEFGHIJKLMN EDFGHIJKLMNNonevOOhappstack-serverTimeoutIO is a record which abstracts out all the network IO functions needed by the request handling loop. This allows use to use the same event loop for handle both http:/ and https:/. OPQRSTUVWX OPQRSTUVWXNoneXx \happstack-serverConnected sockethappstack-server Data receivedYZ[\]^_YZ[\]^_None2=?' bhappstack-server3Convenience class for converting data types to URIsghappstack-server)Retrieves the path component from the URIhhappstack-server*Retrieves the query component from the URIihappstack-server+Retrieves the scheme component from the URIjhappstack-serverDModifies the scheme component of the URI using the provided functionkhappstack-serverBModifies the path component of the URI using the provided functionlhappstack-server$Sets the scheme component of the URImhappstack-server"Sets the path component of the URInhappstack-serverpercent decode a Stringe.g. "hello%2Fworld" ->  "hello/world"qhappstack-server#Returns true if the URI is absoluterhappstack-server.Render should be used for prettyprinting URIs.shappstack-server8Parses a URI from a String. Returns Nothing on failure.`abcdefghijklmnopqrsghijklmnpoqdefrsbc`a None2=?SXjN~happstack-serverCEscape from the HTTP world and get direct access to the underlying O functionshappstack-serverThis class is used by g) to parse a path component into a value. The instances for number types (,  , etc) use  to parse the path component.The instance for <, on the other hand, returns the unmodified path component.gSee the following section of the Happstack Crash Course for detailed instructions using and extending : Fhttp://www.happstack.com/docs/crashcourse/RouteFilters.html#FromReqURIhappstack-serverThe body of an HTTP happstack-server8a class for working with types that contain HTTP headershappstack-serveran HTTP requesthappstack-serverrequest uses https://happstack-serverrequest methodhappstack-server%the uri, split on /, and then decodedhappstack-server the raw rqUrihappstack-serverthe QUERY_STRINGhappstack-server+the QUERY_STRING decoded as key/value pairshappstack-server>the request body decoded as key/value pairs (when appropriate)happstack-servercookieshappstack-server HTTP versionhappstack-serverthe HTTP request headershappstack-serverthe raw, undecoded request bodyhappstack-server1(hostname, port) of the client making the requesthappstack-serveran HTTP Responsehappstack-serverfile handle to send fromhappstack-serveroffset to start athappstack-servernumber of bytes to sendhappstack-serverhostname & porthappstack-servera value extract from the  QUERY_STRING or  bodyUIf the input value was a file, then it will be saved to a temporary file on disk and  will contain Left pathToTempFile.happstack-server Result flagshappstack-serverA flag value set in the  which controls how the Content-Length? header is set, and whether *chunked* output encoding is used. see also: , notContentLength, and happstack-serverautomatically add a Content-Length header to the happstack-server do not add a Content-Length header. Do use chunked output encodinghappstack-server do not set Content-Length or chunked output encoding.happstack-servera Map of HTTP headers0the Map key is the header converted to lowercasehappstack-serveran HTTP headerhappstack-server header namehappstack-serverIheader value (or values if multiple occurances of the header are present)happstack-serverHTTP request methodhappstack-serverHTTP configurationhappstack-server!Port for the server to listen on.happstack-server,a function to validate the output on-the-flyhappstack-server+function to log access requests (see also: )happstack-server;number of seconds to wait before killing an inactive threadhappstack-serverAThreadGroup for registering spawned threads for handling requestshappstack-server+function to log access requests (see also: ) type LogAccess time = ( String -- ^ host -> String -- ^ user -> time -- ^ time -> String -- ^ requestLine -> Int -- ^ responseCode -> Integer -- ^ size -> String -- ^ referer -> String -- ^ userAgent -> IO ())happstack-server HTTP versionhappstack-server if  is HTTP version 1.1happstack-server if  is HTTP version 1.0happstack-serverShould the connection be used for further messages after this. isHTTP1_0 && hasKeepAlive || isHTTP1_1 && hasNotConnectionCloseIn addition to this rule All 1xx (informational), 204 (no content), and 304 (not modified) responses MUST NOT include a message-body and therefore are eligible for connection keep-alive.happstack-serverGDefault configuration contains no validator and the port is set to 8000happstack-serverBlog access requests using hslogger and apache-style log formatting see also: happstack-server'Does the method support a message body?%For extension methods, we assume yes.happstack-server#Default RsFlags: automatically use Transfer-Encoding: Chunked.happstack-server7Do not automatically add a Content-Length field to the happstack-serveraDo not automatically add a Content-Length header. Do automatically use Transfer-Encoding: Chunkedhappstack-serverPAutomatically add a Content-Length header. Do not use Transfer-Encoding: Chunkedhappstack-serverAget the request body from the Request and replace it with NothingVIMPORTANT: You can really only call this function once. Subsequent calls will return .happstack-serverread the request body inputscThis will only work if the body inputs have already been decoded. Otherwise it will return Nothing.happstack-serverCConverts a Request into a String representing the corresponding URLhappstack-serverZSets the Response status code to the provided Int and lifts the computation into a Monad.happstack-servergTakes a list of (key,val) pairs and converts it into Headers. The keys will be converted to lowercasehappstack-server-Lookup header value. Key is case-insensitive.happstack-server:Lookup header value. Key is a case-insensitive bytestring.happstack-serverILookup header value with a case-sensitive key. The key must be lowercase.happstack-serverCLookup header with a case-sensitive key. The key must be lowercase.happstack-server]Returns True if the associated key is found in the Headers. The lookup is case insensitive.happstack-serverActs as  with ByteStringshappstack-serverActs as < but the key is case sensitive. It should be in lowercase.happstack-serverOAssociates the key/value pair in the headers. Forces the key to be lowercase.happstack-serverActs as  but with ByteStrings.happstack-serverSets the key to the HeaderPair. This is the only way to associate a key with multiple values via the setHeader* functions. Does not force the key to be in lowercase or guarantee that the given key and the key in the HeaderPair will match.happstack-serverAdd a key/value pair to the header. If the key already has a value associated with it, then the value will be appended. Forces the key to be lowercase.happstack-server(Acts as addHeader except for ByteStringshappstack-serverAdd a key/value pair to the header using the underlying HeaderPair data type. Does not force the key to be in lowercase or guarantee that the given key and the key in the HeaderPair will match.happstack-servermCreates a Response with the given Int as the status code and the provided String as the body of the Responsehappstack-serverActs as % but works with ByteStrings directly.3By default, Transfer-Encoding: chunked will be usedhappstack-serverOSets the Response's status code to the given Int and redirects to the given URIhappstack-server Locationhappstack-server closehappstack-server  Connectionhappstack-server  Keep-Alivehappstack-serverRead in any monad.happstack-server'convert a 'ReadS a' result to 'Maybe a'happstack-servermodify the headershappstack-serverextract the headershappstack-server(hostname, port)happstack-server$lowercased name -> (realname, value)n%&'()~n%&'()~ None happstack-server headers body!happstack-serversimilar to the normal c function, except the predicate gets the whole rest of the lazy bytestring, not just one character.*TODO: this function has not been profiled..happstack-server1Packs a string into an Input of type "text/plain"/happstack-server'The default content-type for variables.3happstack-serverWCheck whether a string starts with two dashes followed by the given boundary string.4happstack-server/Checks whether a string starts with two dashes.:happstack-server]Split a string at the first CRLF. The CRLF is not included in any of the returned strings.happstack-servertempdirhappstack-serverquotahappstack-serverfilename of fieldhappstack-servercontent to savehappstack-server'truncated?, saved bytes, saved filename3happstack-server(The boundary, without the initial dashes:happstack-serverString to split.happstack-serverReturns  if there is no CRLF.% !"#$%&'()*+,-./0123456789:%!"#$%& '()*+,-./0123456789: None=? ?happstack-serversee FBhappstack-server)maximum bytes for files uploaded in this Chappstack-server-maximum bytes for all non-file values in the  bodyDhappstack-server)maximum bytes of overhead for headers in multipart/form-dataFhappstack-server create a ? for use with decodeBodyHhappstack-serverbDecodes application/x-www-form-urlencoded inputs. TODO: should any of the [] be error conditions?Ihappstack-serverbDecodes application/x-www-form-urlencoded inputs. TODO: should any of the [] be error conditions?Khappstack-server"Decodes multipart/form-data input.Lhappstack-server&Get the path components from a String.Mhappstack-serverIRepeadly splits a list by the provided separator and collects the resultsNhappstack-server1Repeatedly splits a list and collects the resultsOhappstack-server9Split is like break, but the matching element is dropped.Fhappstack-server$temporary directory for file uploadshappstack-server)maximum bytes for files uploaded in this happstack-server-maximum bytes for all non-file values in the  bodyhappstack-server)maximum bytes of overhead for headers in multipart/form-dataKhappstack-serverContent-type parametershappstack-server Request bodyhappstack-serverInput variables and values.(?@BCDAEFGHIJKLMNO?@BCDAEFGHIJKLMNO( None happstack-server+Semantically equivalent to break on stringshappstack-server= behaves like breakChar, but from the end of the ByteString. 2breakCharEnd ('b') (pack "aabbcc") == ("aab","cc")!and the following are equivalent: ibreakCharEnd 'c' "abcdef" let (x,y) = break (=='c') (reverse "abcdef") in (reverse (drop 1 y), reverse x)!None ai%&'()i%&'()"Safe# None=>?@ACHMSVXtPhappstack-serverP? provides a means to end the current computation and return a  immediately. This provides an alternate escape route. In particular it has a monadic value of any type. And unless you call W 7 first your response filters will be applied normally.Extremely useful when you're deep inside a monad and decide that you want to return a completely different content type, since it doesn't force you to convert all your return types to  early just to accommodate this. see also: t and uRhappstack-serverR! is almost exclusively used with l. If you are not using ly then you do not need to wrap your head around this type. If you are -- the type is not as complex as it first appears.1It is worth discussing the unpacked structure of S a bit as it's exposed in l and x.A fully unpacked S! has a structure that looks like: HununWebT $ WebT m a :: m (Maybe (Either Response a, FilterFun Response)) So, ignoring m, as it is just the containing , the outermost layer is a  . This is  if  was called or  (  a, ^ ( )) if  wasn't called. Inside the N, there is a pair. The second element of the pair is our filter function ] . ]  is a type alias for ^ (  ( ))". This is just a wrapper for a  ->  function with a particular   behavior. The value  Append (Dual (Endo f))Causes f) to be composed with the previous filter.  Set (Dual (Endo f))Causes f- to not be composed with the previous filter.1Finally, the first element of the pair is either    or   a.VAnother way of looking at all these pieces is from the behaviors they control. The  controls the  behavior. _ ( f) comes from the W behavior. Likewise, ` ( f) is from X.    is what you get when you call Q and   a is the normal exit.%An example case statement looks like:  ex1 webt = do val <- ununWebT webt case val of Nothing -> Nothing -- this is the interior value when mzero was used Just (Left r, f) -> Just (Left r, f) -- r is the value that was passed into "finishWith" -- f is our filter function Just (Right a, f) -> Just (Right a, f) -- a is our normal monadic value -- f is still our filter functionShappstack-server The basic  building object.Vhappstack-server,A set of functions for manipulating filters.d implements V < so these methods are the fundamental ways of manipulating  values.Whappstack-server/Ignores all previous alterations to your filterAs an example: 9do composeFilter f setFilter g return "Hello World"The W g will cause the first X f to be ignored.Xhappstack-serverAComposes your filter function with the existing filter function.Yhappstack-server*Retrieves the filter from the environment.]happstack-server] is a lot more fun to type than ^ (  ( a)).^happstack-server"A monoid operation container. If a is a monoid, then ^* is a monoid with the following behaviors:  Set x `mappend` Append y = Set (x `mappend` y) Append x `mappend` Append y = Append (x `mappend` y) _ `mappend` Set y = Set y:A simple way of summarizing this is, if the right side is `B, then the right is appended to the left. If the right side is _ , then the left side is ignored.ahappstack-serverThe a> class provides methods for reading or locally modifying the 2. It is essentially a specialized version of the  $ class. Providing the unique names, b and c makes it easier to use d and  together.dhappstack-serverd1 is a rich, featureful monad for web development. see also:  simpleHTTP, a, V, P, and  HasRqDataghappstack-server An alias for d hhappstack-server An alias for S when using .ihappstack-server'Particularly useful when combined with runWebT to produce a m ( ) from a .jhappstack-server(function for lifting WebT to ServerPartTBNOTE: This is mostly for internal use. If you want to access the  in user-code see b from a. do request <- askRq ...khappstack-serverA constructor for a d' when you don't care about the request.NOTE: This is mostly for internal use. If you think you need to use it in your own code, you might consider asking on the mailing list or IRC to find out if there is an alternative solution.lhappstack-server2Apply a function to transform the inner monad of d m.*Often used when transforming a monad with d , since  simpleHTTP requires a d  a . Refer to R3 for an explanation of the structure of the monad.2Here is an example. Suppose you want to embed an  into your d to enable  and  in your . 5type MyServerPartT e m a = ServerPartT (ErrorT e m) aNow suppose you want to pass  MyServerPartT! into a function that demands a d  a (e.g.  simpleHTTP"). You can provide the function: f unpackErrorT :: (Monad m, Show e) => UnWebT (ErrorT e m) a -> UnWebT m a unpackErrorT et = do eitherV <- runErrorT et return $ case eitherV of Left err -> Just (Left $ toResponse $ "Catastrophic failure " ++ show err , filterFun $ \r -> r{rsCode = 500}) Right x -> xWith  unpackErrorT you can now call  simpleHTTP. Just wrap your d list. R simpleHTTP nullConf $ mapServerPartT unpackErrorT (myPart `catchError` myHandler)Or alternatively: B simpleHTTP' unpackErrorT nullConf (myPart `catchError` myHandler) Also see #4 for a more sophisticated version of this function.mhappstack-server A variant of l( where the first argument also takes a . Useful if you want to i on a different d inside your monad (see spUnwrapErrorT).nhappstack-serverImplementation of askRqEnv for arbitrary a.ohappstack-serverImplementation of  localRqEnv for arbitrary a.phappstack-serverExtract the value from a ^. Note that a ^ is actually a  CoPointed from:  hhttp://hackage.haskell.org/packages/archive/category-extras/latest/doc/html/Control-Functor-Pointed.html. But lets not drag in that dependency. yet...rhappstack-serverturn a function into a ]. Primarily used with lshappstack-server&Resets all your filters. An alias for W .thappstack-serverXUsed to ignore all your filters and immediately end the computation. A combination of s and Q.uhappstack-serverAn alternate form of t, that can be easily used within a do block.vhappstack-server%For when you really need to unpack a S5 entirely (and not just unwrap the first layer with U).whappstack-serverFor wrapping a S back up. w . v = xhappstack-serverSee l# for a discussion of this function.yhappstack-server'This is kinda like a very oddly shaped l or x/. You probably want one or the other of those.zhappstack-serverDeprecated: use .{happstack-server3What is this for, exactly? I don't understand why Show ap is even in the context Deprecated: This function appears to do nothing at all. If it use it, let us know why.Qhappstack-servervalue to return (For g, a will always be the type )2PQRSTUVYWXZ[\]^_`acbdefghijklmnopqrstuvwxyz{|}~2hgdefijklmacbno^_`p]qrZ[\VYWXsSTURPQtuvwxyz{|}~ None=>?X޹happstack-server will convert a value into a  body, set the  content-type2, and set the default response code for that type.happstack-server Example: 7main = simpleHTTP nullConf $ toResponse "hello, world!"will generate a  with the content-type  text/plain, the response code 200 OK, and the body:  hello, world!. simpleHTTP will call 1 automatically, so the above can be shortened to: ,main = simpleHTTP nullConf $ "hello, world!"happstack-lite Example: 1main = serve Nothing $ toResponse "hello, world!"Minimal definition:  (and usually ).happstack-server A low-level function to build a  from a content-type and a  ByteString. Creates a  in a manner similar to the 7 class, but without requiring an instance declaration.example: import Data.ByteString.Char8 as C import Data.ByteString.Lazy.Char8 as L import Happstack.Server main = simpleHTTP nullConf $ ok $ toResponseBS (C.pack "text/plain") (L.pack "hello, world")(note: $% and @ only work for ascii. For unicode strings you would need to use  utf8-string, text), or something similar to create a valid  ByteString).happstack-server alias for: fmap toResponseturns m a into m  using . >main = simpleHTTP nullConf $ flatten $ do return "flatten me."happstack-server Honor an if-modified-since header in a  . If the  includes the if-modified-since header and the N has not been modified, then return 304 (Not Modified), otherwise return the .happstack-serverDeprecated: use X.happstack-server.Set an arbitrary return code in your response.WA filter for setting the response code. Generally you will use a helper function like  or . mmain = simpleHTTP nullConf $ do setResponseCode 200 return "Everything is OK" see also: happstack-serverSame as  status >> return val.ZUse this if you want to set a response code that does not already have a helper function. 8main = simpleHTTP nullConf $ resp 200 "Everything is OK"happstack-server Respond with 200 OK. 2main = simpleHTTP nullConf $ ok "Everything is OK"happstack-server Respond with 204 No ContentA 204 No Contenta response may not contain a message-body. If you try to supply one, it will be dutifully ignored. >main = simpleHTTP nullConf $ noContent "This will be ignored."happstack-server Respond with 301 Moved Permanently. |main = simpleHTTP nullConf $ movedPermanently "http://example.org/" "What you are looking for is now at http://example.org/"happstack-server Respond with  302 Found.You probably want j. This method is not in popular use anymore, and is generally treated like 303 by most user-agents anyway.happstack-server Respond with  303 See Other. tmain = simpleHTTP nullConf $ seeOther "http://example.org/" "What you are looking for is now at http://example.org/"NOTE: The second argument of T is the message body which will sent to the browser. According to the HTTP 1.1 spec, dthe entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).lThis is because pre-HTTP/1.1 user agents do not support 303. However, in practice you can probably just use "" as the second argument.happstack-server Respond with 307 Temporary Redirect. main = simpleHTTP nullConf $ tempRedirect "http://example.org/" "What you are looking for is temporarily at http://example.org/"happstack-server Respond with 400 Bad Request. 6main = simpleHTTP nullConf $ badRequest "Bad Request."happstack-server Respond with 401 Unauthorized. Cmain = simpleHTTP nullConf $ unauthorized "You are not authorized."happstack-server Respond with  403 Forbidden. @main = simpleHTTP nullConf $ forbidden "Sorry, it is forbidden."happstack-server Respond with  404 Not Found. Tmain = simpleHTTP nullConf $ notFound "What you are looking for has not been found."happstack-server Respond with 413 Request Entity Too Large. Umain = simpleHTTP nullConf $ requestEntityTooLarge "That's too big for me to handle."happstack-server Respond with 500 Internal Server Error. ]main = simpleHTTP nullConf $ internalServerError "Sorry, there was an internal server error."happstack-serverResponds with 502 Bad Gateway. 6main = simpleHTTP nullConf $ badGateway "Bad Gateway."happstack-server"A nicely formatted rendering of a happstack-server content-typehappstack-server response bodyhappstack-servermod-time for the > (MUST NOT be later than server's time of message origination)happstack-server6incoming request (used to check for if-modified-since)happstack-server+Response to send if there are modificationshappstack-server response codehappstack-server response codehappstack-servervalue to returnNonehappstack-server<Set the validator which should be used for this particular  when validation is enabled.kCalling this function does not enable validation. That can only be done by enabling the validation in the  that is passed to  simpleHTTP.?You do not need to call this function if the validator set in  does what you want already.Example: (use % instead of the default supplied by ) FsimpleHTTP validateConf $ ok . setValidator noopValidator =<< htmlPage See also: , , , .happstack-server ServerPart version of .Example: (Set validator to ) I simpleHTTP validateConf $ setValidatorSP noopValidator (dir "ajax" ... )happstack-serverExtend % by enabling validation and setting  as the default validator for  text/html.Example: 2simpleHTTP validateConf . anyRequest $ ok htmlPagehappstack-server%Actually perform the validation on a .#Run the validator specified in the 7. If none is provide use the supplied default instead.LNote: This function will run validation unconditionally. You probably want  or .happstack-server Validate  text/html content with WDG HTML Validator.1This function expects the executable to be named validate and it must be in the default PATH. See also: , , .happstack-server"A validator which always succeeds.Useful for selectively disabling validation. For example, if you are sending down HTML fragments to an AJAX application and the default validator only understands complete documents.happstack-server Validate the  using an external application.If the external application returns 0, the original response is returned unmodified. If the external application returns non-zero, a O containing the error messages and original response body is returned instead.This function also takes a predicate filter which is applied to the content-type of the response. The filter will only be applied if the predicate returns true.|NOTE: This function requires the use of -threaded to avoid blocking. However, you probably need that for Happstack anyway. See also: .happstack-servername of executablehappstack-server#arguments to pass to the executablehappstack-server"optional path to working directoryhappstack-server(optional environment (otherwise inherit)happstack-servercontent-type filterhappstack-serverResponse to validateNone2> happstack-serverAdd the  to .example xmain = simpleHTTP nullConf $ do addCookie Session (mkCookie "name" "value") ok $ "You now have a session cookie." see also: happstack-server Add the list  to the . see also: happstack-server@Expire the named cookie immediately and set the cookie value to "" ^main = simpleHTTP nullConf $ do expireCookie "name" ok $ "The cookie has been expired."    None2=>?@AM<'happstack-serverUsed by + and *0. Make your preferred data type an instance of  to use those functions.happstack-server#A class for monads which contain a   happstack-server lift some   into   happstack-serverpAn applicative functor and monad for looking up key/value pairs in the QUERY_STRING, Request body, and cookies. happstack-server~the environment used to lookup query parameters. It consists of the triple: (query string inputs, body inputs, cookie inputs) happstack-servera list of errorshappstack-serverapply 'RqData a' to a   see also: *, (, +, ),  , (happstack-server#transform the result of 'RqData a'.This is similar to * except it also allows you to modify the   not just a.happstack-serveruse  to convert a  to a value of type a )look "key" `checkRq` (unsafeReadRq "key") use with NOTE: This function is marked unsafe because some Read instances are vulnerable to attacks that attempt to create an out of memory condition. For example: "read "1e10000000000000" :: Integer see also: happstack-serveruse  to convert a  to a value of type a #look "key" `checkRq` (readRq "key") use with happstack-serverconvert or validate a valueThis is similar to u except that the function can fail by returning Left and an error message. The error will be propagated by calling  .9This function is useful for a number of things including:  Parsing a  into another type]Checking that a value meets some requirements (for example, that is an Int between 1 and 10).Example usage at: ?http://happstack.com/docs/crashcourse/RqData.html#rqdatacheckrqhappstack-serverlike & but the check function can be monadichappstack-server similar to &'+ but returns all matches not just the firsthappstack-server-Gets the first matching named input parameter7Searches the QUERY_STRING followed by the Request body. see also: happstack-server.Gets all matches for the named input parameter7Searches the QUERY_STRING followed by the Request body. see also: happstack-server8Gets the first matching named input parameter as a lazy  ByteString7Searches the QUERY_STRING followed by the Request body. see also: happstack-server7Gets all matches for the named input parameter as lazy  ByteStrings7Searches the QUERY_STRING followed by the Request body. see also: happstack-server3Gets the first matching named input parameter as a 7Searches the QUERY_STRING followed by the Request body.>This function assumes the underlying octets are UTF-8 encoded.Example: lhandler :: ServerPart Response handler = do foo <- look "foo" ok $ toResponse $ "foo = " ++ foo see also: , , and happstack-server2Gets all matches for the named input parameter as s7Searches the QUERY_STRING followed by the Request body.>This function assumes the underlying octets are UTF-8 encoded. see also:  and happstack-server8Gets the first matching named input parameter as a lazy 7Searches the QUERY_STRING followed by the Request body.>This function assumes the underlying octets are UTF-8 encoded. see also: , , , , and happstack-server:Gets the first matching named input parameter as a strict 7Searches the QUERY_STRING followed by the Request body.>This function assumes the underlying octets are UTF-8 encoded. see also: , , , , and happstack-server7Gets all matches for the named input parameter as lazy s7Searches the QUERY_STRING followed by the Request body.>This function assumes the underlying octets are UTF-8 encoded. see also: ,  and happstack-server9Gets all matches for the named input parameter as strict s7Searches the QUERY_STRING followed by the Request body.>This function assumes the underlying octets are UTF-8 encoded. see also: ,  and happstack-server:Gets the named cookie the cookie name is case insensitive happstack-server!gets the named cookie as a string!happstack-server0gets the named cookie as the requested Read type"happstack-serverCGets the first matching named input parameter and decodes it using 7Searches the QUERY_STRING followed by the Request body.>This function assumes the underlying octets are UTF-8 encoded. see also: ##happstack-serverFGets all matches for the named input parameter and decodes them using 7Searches the QUERY_STRING followed by the Request body.>This function assumes the underlying octets are UTF-8 encoded. see also: #$happstack-server"Gets the first matching named filejFiles can only appear in the request body. Additionally, the form must set enctype="multipart/form-data".,This function returns a tuple consisting of: +The temporary location of the uploaded file*The local filename supplied by the browser(The content-type supplied by the browserIf the user does not supply a file in the html form input field, the behaviour will depend upon the browser. Most browsers will send a 0-length file with an empty file name, so checking that (2) is not empty is usually sufficient to ensure the field has been filled.ENOTE: You must move the file from the temporary location before the C is sent. The temporary files are automatically removed after the  is sent.%happstack-server6gets all the input parameters, and converts them to a HThe results will contain the QUERY_STRING followed by the Request body.>This function assumes the underlying octets are UTF-8 encoded. see also: &&happstack-servergets all the input parametersHThe results will contain the QUERY_STRING followed by the Request body. see also: %'happstack-serverThe body of a = is not received or decoded unless this function is invoked.7It is an error to try to use the look functions for a & with out first calling this function.It is ok to call '# at the beginning of every request: umain = simpleHTTP nullConf $ do decodeBody (defaultBodyPolicy "/tmp/" 4096 4096 4096) handlers4You can achieve finer granularity quotas by calling '. with different values in different handlers.Only the first call to 'e will have any effect. Calling it a second time, even with different quota values, will do nothing.(happstack-serverrun   in a a.Example: a simple GET or POSTD variable based authentication guard. It handles the request with  errorHandler if authentication fails. J data AuthCredentials = AuthCredentials { username :: String, password :: String } isValid :: AuthCredentials -> Bool isValid = const True myRqData :: RqData AuthCredentials myRqData = do username <- look "username" password <- look "password" return (AuthCredentials username password) checkAuth :: (String -> ServerPart Response) -> ServerPart Response checkAuth errorHandler = do d <- getDataFn myRqData case d of (Left e) -> errorHandler (unlines e) (Right a) | isValid a -> mzero (Right a) | otherwise -> errorHandler "invalid"NOTE: you must call 'P prior to calling this function if the request method is POST, PUT, PATCH, etc.)happstack-server similar to (/, except it calls a sub-handler on success or  on failure.NOTE: you must call 'P prior to calling this function if the request method is POST, PUT, PATCH, etc.*happstack-server A variant of ( that uses  to chose your   for you. The example from * becomes:  data AuthCredentials = AuthCredentials { username :: String, password :: String } isValid :: AuthCredentials -> Bool isValid = const True myRqData :: RqData AuthCredentials myRqData = do username <- look "username" password <- look "password" return (AuthCredentials username password) instance FromData AuthCredentials where fromData = myRqData checkAuth :: (String -> ServerPart Response) -> ServerPart Response checkAuth errorHandler = do d <- getData case d of (Left e) -> errorHandler (unlines e) (Right a) | isValid a -> mzero (Right a) | otherwise -> errorHandler "invalid"NOTE: you must call 'P prior to calling this function if the request method is POST, PUT, PATCH, etc.+happstack-server similar to *, except it calls a subhandler on success or  on failure.NOTE: you must call 'P prior to calling this function if the request method is POST, PUT, PATCH, etc.,happstack-server#limit the scope to the Request body qhandler :: ServerPart Response handler = do foo <- body $ look "foo" ok $ toResponse $ "foo = " ++ foo-happstack-server#limit the scope to the QUERY_STRING xhandler :: ServerPart Response handler = do foo <- queryString $ look "foo" ok $ toResponse $ "foo = " ++ foo.happstack-serverlimit the scope to s which produce a  ByteString (aka, not a file)happstack-server+name of key (only used for error reporting)happstack-server to happstack-server  on error,   on successhappstack-server+name of key (only used for error reporting)happstack-server to happstack-server  on error,   on success$happstack-server!name of input field to search forhappstack-server;(temporary file location, uploaded file name, content-type)(happstack-server  monad to evaluatehappstack-serverreturn   errors or   a1?@BCDAF      !"#$%&'()*+,-.1"#$%& !,-.'?@BCDAF  ()*+   None>Rhappstack-serverCA class alias for all the classes a standard server monad (such as ds) is expected to have instances for. This allows you to keep your type signatures shorter and easier to understand.Shappstack-server Get a header out of the request.Thappstack-serveruAdd headers into the response. This method does not overwrite any existing header of the same name, hence the name T'. If you want to replace a header use U.Uhappstack-server^Set a header into the response. This will replace an existing header of the same name. Use T; if you want to add more than one header of the same name.Vhappstack-serverSet a far-future Expires header. Useful for static resources. If the browser has the resource cached, no extra request is spent.Whappstack-serverRun an  action and, if it returns ", pass it to the second argument.Xhappstack-server9A variant of require that can run in any monad, not just .PQRVXWYabcdglmrstuRSTUVWXdgRabclmRrVXWYsTSUVPQtuWXNone=?Xchappstack-serverBinstances of this class provide a variety of ways to match on the  method. Examples: >method GET -- match GET or HEAD method [GET, POST] -- match GET, HEAD or POST method HEAD -- match HEAD /but not/ GET method (== GET) -- match GET or HEAD method (not . (==) DELETE) -- match any method except DELETE method () -- match any methodAs you can see, GET implies that HEAD should match as well. This is to make it harder to write an application that uses HTTP incorrectly. Happstack handles HEAD requests automatically, but we still need to make sure our handlers don't mismatch or a HEAD will result in a 404.MIf you must, you can still do something like this to match GET without HEAD: guardRq ((== GET) . rqMethod)ehappstack-server)Guard using an arbitrary function on the .fhappstack-serverCguard which checks that an insecure connection was made via http://Example: ?handler :: ServerPart Response handler = do http ...ghappstack-serverAguard which checks that a secure connection was made via https://Example: @handler :: ServerPart Response handler = do https ...hhappstack-server-Guard against the method only (as opposed to i).Example: Qhandler :: ServerPart Response handler = do methodOnly [GET, HEAD] ...ihappstack-server`Guard against the method. This function also guards against *any remaining path segments*. See h- for the version that guards only by method.Example: Nhandler :: ServerPart Response handler = do methodM [GET, HEAD] ...eNOTE: This function is largely retained for backwards compatibility. The fact that implicitly calls lP is often forgotten and leads to confusion. It is probably better to just use h and call l explicitly.6This function will likely be deprecated in the future.jhappstack-server-Guard against the method only (as opposed to i).Example: Qhandler :: ServerPart Response handler = do methodOnly [GET, HEAD] ...khappstack-serverkGuard against the method. Note, this function also guards against any remaining path segments. Similar to i% but with a different type signature.Example: Jhandler :: ServerPart Response handler = methodSP [GET, HEAD] $ subHandlerbNOTE: This style of combinator is going to be deprecated in the future. It is better to just use h. Thandler :: ServerPart Response handler = method [GET, HEAD] >> nullDir >> subHandlerlhappstack-serverAguard which only succeeds if there are no remaining path segments8Often used if you want to explicitly assign a route for mhappstack-serverPPop a path element and run the supplied handler if it matches the given string. Khandler :: ServerPart Response handler = dir "foo" $ dir "bar" $ subHandler/The path element can not contain '/'. See also n.nhappstack-serverGuard against a  . Unlike m the h may contain '/'. If the guard succeeds, the matched elements will be popped from the directory stack. dirs "foo/bar" $ ... See also: m.ohappstack-serverGuard against the host.This matches against the host" header specified in the incoming .(Can be used to support virtual hosting, ,http://en.wikipedia.org/wiki/Virtual_hosting0Note that this matches against the value of the Host* header which may include the port number. ?http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23 see also: pphappstack-server Lookup the host; header in the incoming request and pass it to the handler. see also: oqhappstack-server*Pop a path element and parse it using the  in the  class.rhappstack-serverGGrab the rest of the URL (dirs + query) and passes it to your handler.shappstack-server)Pop any path element and run the handler.OSucceeds if a path component was popped. Fails is the remaining path was empty.thappstack-server0Guard which checks that the Request URI ends in '/'&. Useful for distinguishing between foo and foo/uhappstack-serverThe opposite of t.cdefghijklmnopqrstufgijkhcdmnltusqropeNone2>SX zhappstack-serversee happstack-servera & from file extensions to content-typesexample: QmyMimeMap :: MimeMap myMimeMap = Map.fromList [("gz","application/x-gzip"), ... ] see also: happstack-server>try to guess the content-type of a file based on its extension see also: happstack-server>try to guess the content-type of a file based on its extension=defaults to "application/octet-stream" if no match was found.Useful as an argument to  see also: , happstack-server9returns a specific content type, completely ignoring the  argument.Use this with 5 if you want to explicitly specify the content-type. see also: , happstack-server,a list of common index files. Specifically:  index.html,  index.xml,  index.gif!Typically used as an argument to  serveDiretory.happstack-server*return a simple "File not found 404 page."happstack-server Similar to  2 but does not include the extension separator charhappstack-serverPrevents files of the form '.foo' or  'bar/.foo' from being servedhappstack-serverReturns True if the given String either starts with a . or is of the form "foo/.bar", e.g. the typical *nix convention for hidden files.happstack-server-Use sendFile to send the contents of a Handlehappstack-server&Send the contents of a Lazy ByteStringhappstack-server&Send the contents of a Lazy ByteStringhappstack-serverESend the specified file with the specified mime-type using sendFile()=NOTE: assumes file exists and is readable by the server. See .*WARNING: No security checks are performed.happstack-serverKSend the specified file with the specified mime-type using lazy ByteStrings=NOTE: assumes file exists and is readable by the server. See .*WARNING: No security checks are performed.happstack-serverMSend the specified file with the specified mime-type using strict ByteStrings=NOTE: assumes file exists and is readable by the server. See .*WARNING: No security checks are performed.happstack-serverServe a single, specified file. The name of the file being served is specified explicity. It is not derived automatically from the  url. example 1:5Serve using sendfile() and the specified content-type RserveFileUsing filePathSendFile (asContentType "image/jpeg") "/srv/data/image.jpg" example 2:OServe using a lazy ByteString and the guess the content-type from the extension OserveFileUsing filePathLazy (guessContentTypeM mimeTypes) "/srv/data/image.jpg"*WARNING: No security checks are performed.happstack-serverServe a single, specified file. The name of the file being served is specified explicity. It is not derived automatically from the  url. example 1:!Serve as a specific content-type: <serveFile (asContentType "image/jpeg") "/srv/data/image.jpg" example 2:3Serve guessing the content-type from the extension: =serveFile (guessContentTypeM mimeTypes) "/srv/data/image.jpg"QIf the specified path does not exist or is not a file, this function will return .*WARNING: No security checks are performed.NOTE: alias for  happstack-serverLike  , but uses [ to prevent directory traversal attacks when the path to the file is supplied by the user.happstack-serverMServe files from a directory and its subdirectories (parameterizable version)5Parameterize this function to create functions like, , , and  You supply: 4a low-level function which takes a content-type and  and generates a Response6a function which determines the content-type from the %a list of all the default index filesANOTE: unlike fileServe, there are no index files by default. See .happstack-server Combine two Fs, ensuring that the resulting path leads to a file within the first .(combineSafe "/var/uploads/" "etc/passwd"Just "/var/uploads/etc/passwd")combineSafe "/var/uploads/" "/etc/passwd"Nothing.combineSafe "/var/uploads/" "../../etc/passwd"Nothing;combineSafe "/var/uploads/" "../uploads/home/../etc/passwd"Just "/var/uploads/etc/passwd"happstack-server:Serve files from a directory and its subdirectories using sendFile.Usage: 0fileServe ["index.html"] "path/to/files/on/disk"* does not support directory browsing. See DEPRECATED: use  instead.Note:The list of index files ["index.html"] is only used to determine what file to show if the user requests a directory. You *do not* need to explicitly list all the files you want to serve.happstack-serverNServe files from a directory and its subdirectories (lazy ByteString version).8WARNING: May leak file handles. You should probably use  instead.happstack-serverPServe files from a directory and its subdirectories (strict ByteString version).\WARNING: the entire file will be read into RAM before being served. You should probably use  instead.happstack-serverattempt to serve index fileshappstack-server1try to find an index file, calls mzero on failurehappstack-serverSa function to generate an HTML page showing the contents of a directory on the disk see also: , happstack-serverTa function to generate an HTML table showing the contents of a directory on the disk4This function generates most of the content of the  page. If you want to style the page differently, or add google analytics code, etc, you can just create a new page template to wrap around this HTML. see also: !, !happstack-server,look up the meta data associated with a filehappstack-serverJServe files and directories from a directory and its subdirectories using sendFile.Usage: DserveDirectory EnableBrowsing ["index.html"] "path/to/files/on/disk"LIf the requested path does not match a file or directory on the disk, then  calls .AIf the requested path is a file then the file is served normally.sIf the requested path is a directory, then the result depends on what the first two arguments to the function are.CThe first argument controls whether directory browsing is enabled.CThe second argument is a list of index files (such as index.html).When a directory is requested,  will first try to find one of the index files (in the order they are listed). If that fails, it will show a directory listing if {# is set, otherwise it will return %forbidden "Directory index forbidden".`Here is an explicit list of all the possible outcomes when the argument is a (valid) directory: |, empty index file list>This will always return, forbidden "Directory index forbidden" |, non-empty index file list +If an index file is found it will be shown.8Otherwise returns, forbidden "Directory index forbidden" {, empty index file listAlways shows a directory index. {, non-empty index file list *If an index file is found it will be shown!Otherwise shows a directory index see also: , happstack-serverlike  but with custom mimeTypeshappstack-serverReady collection of common mime types. Except for the first two entries, the mappings come from an Ubuntu 8.04 /etc/mime.types file.happstack-serverthe content-type to returnhappstack-servercontent-type stringhappstack-serverfile path for content to sendhappstack-servermod-time for the handle (MUST NOT be later than server's time of message origination), incoming request (used to check for if-modified-since header)happstack-serveroffset into Handlehappstack-servernumber of bytes to sendhappstack-servercontent-type string (e.g. "text/plain; charset=utf-8")happstack-serverlazy bytestring content to sendhappstack-serverZmod-time for the bytestring, incoming request (used to check for if-modified-since header)happstack-serveroffset into the bytestringhappstack-servercnumber of bytes to send (offset + count must be less than or equal to the length of the bytestring)happstack-servercontent-type string (e.g. "text/plain; charset=utf-8")happstack-serverlazy bytestring content to sendhappstack-serverZmod-time for the bytestring, incoming request (used to check for if-modified-since header)happstack-serveroffset into the bytestringhappstack-servercnumber of bytes to send (offset + count must be less than or equal to the length of the bytestring)happstack-servercontent-type stringhappstack-serverpath to file on diskhappstack-servercontent-type stringhappstack-serverpath to file on diskhappstack-servercontent-type stringhappstack-serverpath to file on diskhappstack-server typically , , or happstack-server9function for determining content-type of file. Typically  or happstack-serverpath to the file to servehappstack-server9function for determining content-type of file. Typically  or happstack-serverpath to the file to servehappstack-server0directory wherein served files must be containedhappstack-server9function for determining content-type of file. Typically  or happstack-serverpath to the file to servehappstack-serverUfunction which takes a content-type and filepath and generates a response (typically , , or )happstack-serverfunction which returns the mime-type for FilePath -> [FilePath] -- ^ index file names, in case the requested path is a directoryhappstack-serverfile/directory to servehappstack-server;index file names, in case the requested path is a directoryhappstack-serverfile/directory to servehappstack-server;index file names, in case the requested path is a directoryhappstack-serverfile/directory to servehappstack-server:index file names, in case the next argument is a directoryhappstack-serverfile/directory to servehappstack-server$list of possible index files (e.g.,  index.html)happstack-server see also happstack-server+directory on disk to search for index fileshappstack-serverusually happstack-server)function to calculate mime type, usually happstack-serverlist of index files. See also happstack-serverdirectory to search inhappstack-serverpath to directory on diskhappstack-serverlist of entries in that pathhappstack-serverlist of files+meta data, see !!happstack-server.path to directory on disk containing the entryhappstack-serverentry in that directoryhappstack-serverallow directory browsinghappstack-server;index file names, in case the requested path is a directoryhappstack-serverfile/directory to servehappstack-serverallow directory browsinghappstack-server;index file names, in case the requested path is a directoryhappstack-server1function which returns the mime-type for FilePathhappstack-serverfile/directory to serve)z{|}~)z{|}~(None z{| z{|NoneWhappstack-serverFlatten d ( e m) a into a d m a so that it can be use with  simpleHTTP. Used with mapServerPartT', e.g., fsimpleHTTP conf $ mapServerPartT' (spUnWrapErrorT simpleErrorHandler) $ myPart `catchError` errorPartNote that in this example, simpleErrorHandler will only be run if  errorPart" throws an error. You can replace simpleErrorHandler$ with your own custom error handler. see also: happstack-server.A simple error handler which can be used with .It returns the error message as a plain text message to the browser. More sophisticated behaviour can be achieved by calling your own custom error handler instead. see also: happstack-serverThis  ServerPart modifier enables the use of  throwError and  catchError inside the S actions, by adding the ! monad transformer to the stack.-You can wrap the complete second argument to  simpleHTTP in this function.DEPRECATED: use  instead.None>7happstack-server)A simple HTTP basic authentication guard.-If authentication fails, this part will call .example: main = simpleHTTP nullConf $ msum [ basicAuth "127.0.0.1" (fromList [("happstack","rocks")]) $ ok "You are in the secret club" , ok "You are not in the secret club." ]happstack-serverthe realm namehappstack-serverthe username password maphappstack-serverthe part to guardNonePXHhappstack-serverSUnserializes the bytestring into a response. If there is an error it will return Left msg.happstack-server*Serializes the request to the given handleNoneX3happstack-serverBind and listen porthappstack-server%Use a previously bind port and listenhappstack-server?IP address to listen on (must be an IP address not a host name)happstack-serverport number to listen on)Noneu%&'()~Nonehappstack-servermSends the serialized request to the host defined in the request and attempts to parse response upon arrival.None>/happstack-serverB is for creating a part that acts as a proxy. The sole argument [] is a list of allowed domains for proxying. This matches the domain part of the request and the wildcard * can be used. E.g."*" to match anything.3"*.example.com" to match anything under example.com'"example.com" to match just example.com6TODO: annoyingly enough, this method eventually calls escapeQ, so any headers you set won't be used, and the computation immediately ends.happstack-server Take a proxy  and create a *. Your basic proxy building block. See .2TODO: this would be more useful if it didn't call escapeN (e.g. it let you modify the response afterwards, or set additional headers)happstack-server-This is a reverse proxy implementation. See .2TODO: this would be more useful if it didn't call escape , just like .happstack-server defaultHosthappstack-server8map to look up hostname mappings. For the reverse proxyhappstack-serverthe result is a  ServerPartT! that will reverse proxy for you.*(c) Happstack.com 2010; (c) HAppS Inc 2007BSD-like'Happstack team <happs@googlegroups.com> provisional requires mtlNone =>?@ACMX8 "happstack-server An array of #6, useful for processing command line options into an  for .happstack-server"Parse command line options into a .happstack-server:start the server, and handle requests using the supplied g.@This function will not return, though it may throw an exception.LNOTE: The server will only listen on IPv4 due to portability issues in the Network module. For IPv6 support, use  with custom socket.happstack-serverA combination of  and l. See l: for a discussion of the first argument of this function.vNOTE: This function always binds to IPv4 ports until Network module is fixed to support IPv6 in a portable way. Use 5 with custom socket if you want different behaviour.happstack-serverGenerate a result from a d and a 6. This is mainly used by CGI (and fast-cgi) wrappers.happstack-serverRun r with a previously bound socket. Useful if you want to run happstack as user on port 80. Use something like this: _import System.Posix.User (setUserID, UserEntry(..), getUserEntryForName) main = do let conf = nullConf { port = 80 } socket <- bindPort conf -- do other stuff as root here getUserEntryForName "www" >>= setUserID . userID -- finally start handling incoming requests tid <- forkIO $ simpleHTTPWithSocket socket Nothing conf implKNote: It's important to use the same conf (or at least the same port) for  and . see also: , happstack-serverLike  with a socket.happstack-server-Bind port and return the socket for use with m. This function always binds to IPv4 ports until Network module is fixed to support IPv6 in a portable way.happstack-server7Bind to ip and port and return the socket for use with .  import Happstack.Server main = do let conf = nullConf addr = "127.0.0.1" s <- bindIPv4 addr (port conf) simpleHTTPWithSocket s conf $ ok $ toResponse $ "now listening on ip addr " ++ addr ++ " and port " ++ show (port conf)$happstack-server Takes your S , if it is % it returns " else it converts the value to a  and applies your filter to it.happstack-serverMWait for a signal. On unix, a signal is sigINT or sigTERM (aka Control-C).&On windows, the signal is entering: e returnhappstack-serverAIP address to bind to (must be an IP address and not a host name)happstack-serverport number to bind to   %&'()?@BCDAFPQRVXWYabcdglmrstu      !"#$%&'()*+,-.RSTUVWXcdefghijklmnopqrstu None>% happstack-server reads the Accept-EncodingJ header. Then, if possible will compress the response body with methods gzip or deflate.This function uses [. If you want to provide alternative handers (perhaps to change compression levels), see  main = simpleHTTP nullConf $ do str <- compressedResponseFilter return $ toResponse ("This response compressed using: " ++ str)happstack-server reads the Accept-Encoding_ header. Then, if possible will compress the response body using one of the supplied filters.6A filter function takes two arguments. The first is a # with the value to be used as the 'Content-Encoding' header. The second is &F which indicates if the compression filter is allowed to fallback to identity.wThis is important if the resource being sent using sendfile, since sendfile does not provide a compression option. If identityM is allowed, then the file can be sent uncompressed using sendfile. But if identity@ is not allowed, then the filter will need to return error 406.'You should probably always include the identity and * encodings as acceptable. pmyFilters :: (FilterMonad Response m) => [(String, String -> Bool -> m ()] myFilters = [ ("gzip" , gzipFilter) , ("identity", identityFilter) , ("*" , starFilter) ] main = simpleHTTP nullConf $ do let filters = str <- compressedResponseFilter' return $ toResponse ("This response compressed using: " ++ str)happstack-server Ignore the Accept-Encoding header in the 7 and attempt to compress the body of the response with gzip.calls  using '. see also: happstack-server Ignore the Accept-Encoding header in the < and attempt compress the body of the response with zlib's deflate methodcalls  using (. see also: happstack-server>compression filter for the identity encoding (aka, do nothing) see also: happstack-server%compression filter for the * encodingThis filter always fails.happstack-server Ignore the Accept-Encoding header in the P and attempt to compress the body of the response using the supplied compressor.1We can not compress files being transfered using . If identity. is an allowed encoding, then just return the " unmodified. Otherwise we return 406 Not Acceptable. see also: , , , , )happstack-server0based on the rules describe in rfc2616 sec. 14.3happstack-serverJan assoc list of encodings and their corresponding compression functions.e.g. F[("gzip", gzipFilter), ("identity", identityFilter), ("*",starFilter)]happstack-server'a parser for the Accept-Encoding headerhappstack-servername of the encoding chosenhappstack-servercompression filter assoc listhappstack-servername of the encoding chosenhappstack-server+encoding to use for Content-Encoding headerhappstack-server!fallback to identity for SendFilehappstack-server+encoding to use for Content-Encoding headerhappstack-server!fallback to identity for SendFilehappstack-server+encoding to use for Content-Encoding headerhappstack-server>fallback to identity for SendFile (irrelavant for this filter)happstack-server+encoding to use for Content-Encoding headerhappstack-server>fallback to identity for SendFile (irrelavant for this filter)happstack-serverfunction to compress the bodyhappstack-server+encoding to use for Content-Encoding headerhappstack-server!fallback to identity for SendFile  None,happstack-server parse the 'Accept-Language' header, or [] if not found.happstack-serverdeconstruct the P results a return a list of languages sorted by preference in descending order.5Note: this implementation does not conform to RFC4647wAmong other things, it does not handle wildcards. A proper implementation needs to take a list of available languages.*None>,p+*(c) Happstack.com 2010; (c) HAppS Inc 2007BSD3'Happstack team <happs@googlegroups.com> provisional'GHC-only, Windows, Linux, FreeBSD, OS XNone/  %&'()?@BCDAFPQRVXWYabcdglmrstu      !"#$%&'()*+,-.RSTUVWXcdefghijklmnopqrstuz{| *,-./01123456789:;<=>?@ABCDEFGHIJKLLMMNNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwwxyz{|}~                                                                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ \ ] ^ _ ` a b c d e f g h i j k l m n o o p q r s t u u v w x y z { | } ~ ~                                                                                                                                                      !"#$%&&'()*+,-./0123456789:;<=>f?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~#              """""""" !" #$ %&'()(*+&,&-./01234156.78.79:;<% =>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\Z]\^_-happstack-server-7.5.3-Km1BEDZUTMAFVDGqkE8JHR Happstack.Server.Internal.Cookie#Happstack.Server.Internal.LogFormat'Happstack.Server.Internal.RFC822Headers Happstack.Server.Internal.Socket(Happstack.Server.Internal.TimeoutManager#Happstack.Server.Internal.TimeoutIO'Happstack.Server.Internal.TimeoutSocketHappstack.Server.SURIHappstack.Server.Internal.Types#Happstack.Server.Internal.Multipart%Happstack.Server.Internal.MessageWrap Happstack.Server.Internal.MonadsHappstack.Server.ResponseHappstack.Server.ValidationHappstack.Server.CookieHappstack.Server.RqDataHappstack.Server.MonadsHappstack.Server.Routing)Happstack.Server.FileServe.BuildingBlocksHappstack.Server.ErrorHappstack.Server.Auth!Happstack.Server.Internal.Handler Happstack.Server.Internal.ListenHappstack.Server.ClientHappstack.Server.ProxyHappstack.Server.SimpleHTTP%Happstack.Server.Internal.CompressionHappstack.Server.I18NHappstack.Server.Internal.Clock#Happstack.Server.Internal.LazyLiner"Happstack.Server.Internal.SocketTHHappstack.Server.SURI.ParseURIHappstack.Server.TypesPaths_happstack_serverspUnwrapErrorTCpack Data.ListlookupHappstack.Server.FileServe"Happstack.Server.Internal.LowLevelHappstack.Server.CompressionHappstack.Server CookieLifeSessionMaxAgeExpiresExpiredCookie cookieVersion cookiePath cookieDomain cookieName cookieValuesecurehttpOnlycalcLifemkCookiemkCookieHeader parseCookies cookiesParser getCookies getCookie getCookies' getCookie' $fShowCookie $fEqCookie $fReadCookie $fDataCookie$fEqCookieLife$fOrdCookieLife$fReadCookieLife$fShowCookieLifeformatTimeCombinedformatRequestCombinedContentDispositionContentTransferEncoding ContentTypectType ctSubtype ctParametersHeaderpHeaders parseHeaderspHeadershowContentTypeparseContentTypegetContentTypeparseContentTransferEncodinggetContentTransferEncodingparseContentDispositiongetContentDispositionparseM$fShowContentType$fReadContentType$fEqContentType$fOrdContentType$fShowContentTransferEncoding$fReadContentTransferEncoding$fEqContentTransferEncoding$fOrdContentTransferEncoding$fShowContentDisposition$fReadContentDisposition$fEqContentDisposition$fOrdContentDisposition acceptLitesockAddrToPeerHandleManager initializeregisterregisterKillThreadticklepauseresumecancel forceTimeoutforceTimeoutAll TimeoutIOtoHandle toPutLazytoPuttoGet toGetContents toSendFile toShutdowntoSecuresPutLazyTickle sPutTicklesGet sGetContentssendFileTickle iterTickletimeoutSocketIOFromPathfromPathToSURItoSURISURIsuripathqueryschemeu_schemeu_patha_schemea_path percentDecode unEscapeQSunEscapeisAbsrenderparse $fOrdSURI $fReadSURI $fShowSURI $fToSURIText $fToSURIText0 $fToSURI[] $fToSURIURI $fToSURISURI$fEqSURI $fDataSURI EscapeHTTP FromReqURI fromReqURIRqBodyBodyunBodyRequestrqSecurerqMethodrqPathsrqUrirqQuery rqInputsQuery rqInputsBody rqCookies rqVersion rqHeadersrqBodyrqPeerResponseSendFilersCode rsHeadersrsFlagsrsBody rsValidator sfFilePathsfOffsetsfCountHostInput inputValue inputFilenameinputContentTypeRsFlags rsfLengthLength ContentLengthTransferEncodingChunkedNoContentLengthHeaders HeaderPairhNamehValueMethodGETHEADPOSTPUTDELETETRACEOPTIONSCONNECTPATCH EXTENSIONConfport validator logAccesstimeout threadGroup LogAccess HttpVersion isHTTP1_1 isHTTP1_0 continueHTTPnullConf logMAccess canHaveBody nullRsFlagsnoContentLengthchunked contentLengthshowRsValidatortakeRequestBodyreadInputsBodyrqURL setRsCode mkHeaders getHeader getHeaderBSgetHeaderUnsafe hasHeader hasHeaderBShasHeaderUnsafe setHeader setHeaderBSsetHeaderUnsafe addHeader addHeaderBSaddHeaderUnsaferesultresultBSredirectreadDec'readM fromReadS$fShowHttpVersion$fErrorResponse$fShowResponse$fHasHeadersMap$fHasHeadersResponse$fHasHeadersRequest $fShowRequest$fFromReqURIBool$fFromReqURIDouble$fFromReqURIFloat$fFromReqURIWord64$fFromReqURIWord32$fFromReqURIWord16$fFromReqURIWord8$fFromReqURIWord$fFromReqURIInteger$fFromReqURIInt64$fFromReqURIInt32$fFromReqURIInt16$fFromReqURIInt8$fFromReqURIInt$fFromReqURIChar$fFromReqURIText$fFromReqURIText0$fFromReqURI[]$fShowEscapeHTTP$fExceptionEscapeHTTP$fReadHttpVersion$fEqHttpVersion $fShowMethod $fReadMethod $fEqMethod $fOrdMethod $fDataMethod$fReadHeaderPair$fShowHeaderPair $fEqLength $fOrdLength $fReadLength $fShowLength $fEnumLength $fShowRsFlags $fReadRsFlags $fShowInput $fReadInput $fReadRqBody $fShowRqBody FileSaver InputIterFailed BodyResult HeaderResult InputWorkerWorkBodyWork HeaderWorkBodyPartspanS takeWhileScrlfcrlfcrlf blankLine dropWhileSdefaultFileSaverdefaultInputIter hPutLimit hPutLimit'bodyPartToInputbodyPartsToInputs multipartBody simpleInputdefaultInputTypeparseMultipartBody dropPreambledropLine isBoundarystartsWithDashes splitParts splitPart splitBlank splitBoundarysplitAtEmptyLine splitAtCRLF $fEqBodyPart $fOrdBodyPart$fReadBodyPart$fShowBodyPart BodyPolicy inputWorkermaxDiskmaxRAM maxHeader queryInputdefaultBodyPolicy bodyInput formDecode formDecodeBS decodeBodymultipartDecodepathEls splitList splitListBysplitWebMonad finishWithUnWebTWebTunWebT FilterMonad setFilter composeFilter getFilterFilterT unFilterT FilterFun SetAppendSetAppend ServerMonadaskRqlocalRq ServerPartT unServerPartT ServerPartWebrunServerPartT withRequest anyRequestmapServerPartTmapServerPartT' smAskRqEnv smLocalRqEnvextract unFilterFun filterFun ignoreFiltersescapeescape'ununWebTmkWebTmapWebT localContextmulti debugFilteroutputTraceMessage mkFailMessage failResponsefailHtml escapeString escapeHTTP$fServerMonadExceptT$fServerMonadErrorT$fServerMonadRWST$fServerMonadRWST0$fServerMonadWriterT$fServerMonadWriterT0$fServerMonadStateT$fServerMonadStateT0$fServerMonadReaderT$fFunctorSetAppend$fMonoidSetAppend$fSemigroupSetAppend$fMonadBaseControlbFilterT$fMonadTransControlFilterT$fMonadIOFilterT$fMonadBasebFilterT$fMonadThrowFilterT$fMonadCatchFilterT$fFilterMonadaExceptT$fFilterMonadaErrorT$fFilterMonadresRWST$fFilterMonadresRWST0$fFilterMonadresWriterT$fFilterMonadresWriterT0$fFilterMonadresStateT$fFilterMonadresStateT0$fFilterMonadresReaderT$fFilterMonadaFilterT$fMonadWriterwWebT$fMonadErroreWebT$fMonadStatestWebT$fMonadReaderrWebT$fAlternativeWebT$fApplicativeWebT $fMonoidWebT$fSemigroupWebT$fFilterMonadResponseWebT$fMonadPlusWebT$fMonadTransWebT $fMonadWebT$fMonadBaseControlbWebT$fMonadTransControlWebT $fMonadIOWebT$fMonadBasebWebT$fMonadThrowWebT$fMonadCatchWebT$fMonadFailWebT$fServerMonadServerPartT $fFilterMonadResponseServerPartT$fMonadStatesServerPartT$fMonadReaderrServerPartT$fMonadErroreServerPartT$fMonadWriterwServerPartT$fAlternativeServerPartT$fApplicativeServerPartT$fMonoidServerPartT$fSemigroupServerPartT$fMonadTransServerPartT$fMonadBaseControlbServerPartT$fMonadTransControlServerPartT$fMonadIOServerPartT$fMonadBasebServerPartT$fMonadThrowServerPartT$fMonadCatchServerPartT$fWebMonadaExceptT$fWebMonadaErrorT$fWebMonadaRWST$fWebMonadaRWST0$fWebMonadaWriterT$fWebMonadaWriterT0$fWebMonadaStateT$fWebMonadaStateT0$fWebMonadaReaderT$fWebMonadResponseWebT$fWebMonadResponseServerPartT $fEqSetAppend$fShowSetAppend$fFunctorFilterT$fApplicativeFilterT$fMonadFilterT$fMonadTransFilterT $fFunctorWebT$fMonadServerPartT$fMonadFailServerPartT$fMonadPlusServerPartT$fFunctorServerPartT ToMessage toContentType toMessage toResponse toResponseBSflattenifModifiedSincesetResponseCoderespok noContentmovedPermanentlyfoundseeOther tempRedirect badRequest unauthorized forbiddennotFoundrequestEntityTooLargeinternalServerError badGatewayprettyResponse$fToMessageByteString$fToMessageByteString0$fToMessageResponse$fToMessageMarkupM$fToMessageHtml$fToMessageHtml0$fToMessageMaybe$fToMessageInteger$fToMessageText$fToMessageText0 $fToMessage[] $fToMessage() setValidatorsetValidatorSP validateConf runValidatorwdgHTMLValidator noopValidatorlazyProcValidator addCookie addCookies expireCookieFromDatafromData HasRqDataaskRqEnv localRqEnv rqDataErrorRqDataRqEnvErrorsunErrors mapRqData unsafeReadRqreadRqcheckRqcheckRqM lookInput lookInputslookBSlookBSslooklookslookText lookText' lookTexts lookTexts' lookCookielookCookieValuereadCookieValuelookRead lookReadslookFile lookPairs lookPairsBS getDataFn withDataFngetDatawithDatabody queryString bytestring$fAlternativeReaderError$fApplicativeReaderError$fMonadReaderrReaderError $fErrorErrors$fMonoidErrors$fSemigroupErrors$fHasRqDataExceptT$fHasRqDataErrorT$fHasRqDataRWST$fHasRqDataRWST0$fHasRqDataWriterT$fHasRqDataWriterT0$fHasRqDataStateT$fHasRqDataStateT0$fHasRqDataReaderT$fHasRqDataServerPartT$fHasRqDataRqData$fFromDataMaybe$fFromData(,,,)$fFromData(,,) $fFromData(,)$fFunctorReaderError$fMonadReaderError$fMonadPlusReaderError $fEqErrors $fOrdErrors $fShowErrors $fReadErrors $fDataErrors$fFunctorRqData $fMonadRqData$fMonadPlusRqData$fApplicativeRqData$fAlternativeRqData$fMonadReaderRqData Happstack getHeaderM addHeaderM setHeaderM neverExpiresrequirerequireM$fHappstackExceptT$fHappstackErrorT$fHappstackRWST$fHappstackRWST0$fHappstackWriterT$fHappstackWriterT0$fHappstackReaderT$fHappstackStateT$fHappstackStateT0$fHappstackServerPartT MatchMethod matchMethodguardRqhttphttpsmethodmethodM methodOnlymethodSPnullDirdirdirshostwithHosturiRestanyPath trailingSlashnoTrailingSlash$fMatchMethod()$fMatchMethod->$fMatchMethod[]$fMatchMethodMethodBrowsingEnableBrowsingDisableBrowsing EntryKindFile Directory UnknownKindMimeMapguessContentTypeguessContentTypeM asContentTypedefaultIxFiles fileNotFound blockDotFilesisDotsendFileResponselazyByteStringResponsestrictByteStringResponsefilePathSendFile filePathLazyfilePathStrictserveFileUsing serveFile serveFileFrom fileServe' combineSafe isSafePath fileServe fileServeLazyfileServeStrictdoIndex doIndexLazy doIndexStrictdoIndex'tryIndex browseIndexrenderDirectoryContentsrenderDirectoryContentsTableserveDirectoryserveDirectory' mimeTypes $fEqEntryKind$fOrdEntryKind$fReadEntryKind$fShowEntryKind$fDataEntryKind$fEnumEntryKind $fEqBrowsing$fEnumBrowsing $fOrdBrowsing$fReadBrowsing$fShowBrowsing$fDataBrowsingsimpleErrorHandlererrorHandlerSP basicAuthrequest parseResponse putRequestlistenOn listenOnIPv4listenlisten' getResponse proxyServe proxyServe' rproxyServe unproxify unrproxify parseConfig simpleHTTP simpleHTTP' simpleHTTP''simpleHTTPWithSocketsimpleHTTPWithSocket'bindPortbindIPv4waitForTerminationcompressedResponseFiltercompressedResponseFilter' gzipFilter deflateFilteridentityFilter starFiltercompressWithFilterstandardEncodingHandlers encodingsacceptLanguage bestLanguageformatHttpDategetApproximateTimegetApproximatePOSIXTimegetApproximateUTCTimebytestring-0.10.8.2Data.ByteString.LazytoChunksLazynewLinerHandle headerLinesgetBytesStrictgetBytesgetRestbaseGHC.Num+-GHC.ShowShowGHC.Basefailws1crLf lineString supportsIPv6showHostAddressshowHostAddress6ghc-prim GHC.TypesIntFloatString HasHeadersTrue GHC.MaybeNothinggetHeaderUnsafe' locationCcloseC connectionC keepaliveC updateHeadersheadersGHC.Listspan breakChar breakCharEnd parseURIRefversion getBinDir getLibDir getDynLibDir getDataDir getLibexecDir getSysconfDirgetDataFileNameidMonadMaybemzeroJust Data.EitherEitherData.Semigroup.InternalEndoDualMonoidLeftRight mtl-2.2.2Control.Monad.Reader.Class MonadReadertransformers-0.5.5.0Control.Monad.Trans.ReaderReaderTIOControl.Monad.Trans.ErrorErrorTControl.Monad.Error.Class throwError catchError Data.FoldablemsumData.ByteString.Lazy.Char8modifyResponse runRqDatafmap Text.Readreadlookups text-1.2.3.1Data.Text.InternalTextGHC.ReadReadGHC.Real/GHC.IOFilePathcontainers-0.6.0.1Data.Map.InternalMapgetExtfilepath-1.4.2.1System.FilePath.Posix takeExtension getMetaDatahoSystem.Console.GetOptOptDescrrunWebTmemptyBool#zlib-0.6.2.1-JkgnCzQLE4d9AnItMNCDCpCodec.Compression.GZipcompressCodec.Compression.Zlib bestEncoding