]> gitweb @ CieloNegro.org - Lucu.git/blob - Network/HTTP/Lucu/Httpd.hs
Documentation
[Lucu.git] / Network / HTTP / Lucu / Httpd.hs
1 -- | The entry point of Lucu httpd.
2 module Network.HTTP.Lucu.Httpd
3     ( runHttpd
4     )
5     where
6
7 import           Control.Concurrent
8 import           Network
9 import           Network.HTTP.Lucu.Config
10 import           Network.HTTP.Lucu.Interaction
11 import           Network.HTTP.Lucu.RequestReader
12 import           Network.HTTP.Lucu.Resource.Tree
13 import           Network.HTTP.Lucu.ResponseWriter
14 import           System.Posix.Signals
15
16 -- | This is the entry point of Lucu httpd. It listens to a socket and
17 -- waits for clients. Computation of 'runHttpd' never stops by itself
18 -- so the only way to stop it is to raise an exception in the thread
19 -- computing it.
20 --
21 -- Note that 'runHttpd' automatically makes SIGPIPE be ignored by
22 -- computing @installHandler sigPIPE Ignore Nothing@. This can hardly
23 -- cause a problem but it may do.
24 --
25 -- Example:
26 --
27 -- > module Main where
28 -- > import Network.HTTP.Lucu
29 -- > 
30 -- > main :: IO ()
31 -- > main = let config    = defaultConfig
32 -- >            resources = mkResTree [ ([], helloWorld) ]
33 -- >        in
34 -- >          runHttpd config resourcees
35 -- >
36 -- > helloWorld :: ResourceDef
37 -- > helloWorld = ResourceDef {
38 -- >                resUsesNativeThread = False
39 -- >              , resIsGreedy         = False
40 -- >              , resGet
41 -- >                  = Just $ do setContentType $ "text" </> "plain"
42 -- >                              output "Hello, world!"
43 -- >              , resHead   = Nothing
44 -- >              , resPost   = Nothing
45 -- >              , resPut    = Nothing
46 -- >              , resDelete = Nothing
47 -- >              }
48 runHttpd :: Config -> ResTree -> IO ()
49 runHttpd cnf tree
50     = withSocketsDo $
51       do installHandler sigPIPE Ignore Nothing
52          so <- listenOn (cnfServerPort cnf)
53          loop so
54     where
55       loop :: Socket -> IO ()
56       loop so
57           = do (h, host, _) <- accept so
58                tQueue       <- newInteractionQueue
59                readerTID    <- forkIO $ requestReader cnf tree h host tQueue
60                writerTID    <- forkIO $ responseWriter cnf h tQueue readerTID
61                loop so