on warp-tls/1.3.0 help sign in
typeable/wai/wai/README.lhs
113 lines 2.8 kB history raw
1WAI: Web Application Interface
2==============================
4Getting started
5---------------
7You want a minimal example? Here it is!
9> {-# LANGUAGE OverloadedStrings #-}
10> import Network.Wai
11> import Network.HTTP.Types
12> import Network.Wai.Handler.Warp (run)
13> import Data.ByteString.Lazy.Char8 () -- Just for an orphan instance
14> import Control.Monad.IO.Class (liftIO)
16> app :: Application
17> app _ = do
18> liftIO $ putStrLn "I've done some IO here"
19> return $ responseLBS
20> status200
21> [("Content-Type", "text/plain")]
22> "Hello, Web!"
24> main :: IO ()
25> main = do
26> putStrLn $ "http://localhost:8080/"
27> run 8080 app
29Put that code into a file named _hello.hs_ and install [wai] and
30[warp] from Hackage:
32 cabal install wai warp
34Run it:
36 runhaskell hello.hs
38Point your browser to:
40 http://localhost:8080/
43Serving static content
44----------------------
46We can modify our previous example to serve static content. For this
47create a file named _index.html_:
49 <p>Hello, Web!</p>
51Now we redefine `responseBody` to refer to that file:
53> app2 :: Application
54> app2 _ = return index
56> index = ResponseFile
57> status200
58> [("Content-Type", "text/html")]
59> "index.html"
60> Nothing
63Basic dispatching
64-----------------
66An `Application` maps `Request`s to `Response`s:
68 ghci> :info Application
69 type Application = Request -> IO Response
71Depending on the path info provided with each `Request` we can serve
72different `Response`s:
74> app3 :: Application
75> app3 request = case rawPathInfo request of
76> "/" -> return index
77> "/raw/" -> return plainIndex
78> _ -> return notFound
80> plainIndex = ResponseFile
81> status200
82> [("Content-Type", "text/plain")]
83> "index.html"
84> Nothing
86> notFound = responseLBS
87> status404
88> [("Content-Type", "text/plain")]
89> "404 - Not Found"
92Doing without overloaded strings
93--------------------------------
95For the sake of efficiency, WAI uses the [bytestring] package. We used
96GHCs [overloaded strings] to almost hide this fact. But we can easily do
97without. What follows is a more verbose definition of `notFound`, that
98works without GHC extensions:
100 import qualified Data.ByteString.Char8 as B8
101 import qualified Data.ByteString.Lazy.Char8 as LB8
102 import Data.CaseInsensitive (mk)
104 notFound = responseLBS
105 status404
106 [(mk $ B8.pack "Content-Type", B8.pack "text/plain")]
107 (LB8.pack "404 - Not Found")
110 [wai]: http://hackage.haskell.org/package/wai
111 [warp]: http://hackage.haskell.org/package/warp
112 [overloaded strings]: http://www.haskell.org/ghc/docs/latest/html/users_guide/type-class-extensions.html#overloaded-strings
113 [bytestring]: http://hackage.haskell.org/package/bytestring