]> gitweb @ CieloNegro.org - Lucu.git/blob - Network/HTTP/Lucu/Httpd.hs
cbbb517abf2d98effe2dc806d1ebef7904fc204b
[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 qualified Network.Socket as So
10 import           Network.HTTP.Lucu.Config
11 import           Network.HTTP.Lucu.Interaction
12 import           Network.HTTP.Lucu.RequestReader
13 import           Network.HTTP.Lucu.Resource.Tree
14 import           Network.HTTP.Lucu.ResponseWriter
15 import           System.IO
16 import           System.Posix.Signals
17
18 -- |This is the entry point of Lucu httpd. It listens to a socket and
19 -- waits for clients. Computation of 'runHttpd' never stops by itself
20 -- so the only way to stop it is to raise an exception in the thread
21 -- computing it.
22 --
23 -- Note that 'runHttpd' automatically makes SIGPIPE be ignored by
24 -- computing @'System.Posix.Signals.installHandler'
25 -- 'System.Posix.Signals.sigPIPE' 'System.Posix.Signals.Ignore'
26 -- 'Prelude.Nothing'@. This can hardly cause a problem but it may do.
27 --
28 -- Example:
29 --
30 -- > module Main where
31 -- > import Network.HTTP.Lucu
32 -- > 
33 -- > main :: IO ()
34 -- > main = let config    = defaultConfig
35 -- >            resources = mkResTree [ ([], helloWorld) ]
36 -- >        in
37 -- >          runHttpd config resourcees
38 -- >
39 -- > helloWorld :: ResourceDef
40 -- > helloWorld = ResourceDef {
41 -- >                resUsesNativeThread = False
42 -- >              , resIsGreedy         = False
43 -- >              , resGet
44 -- >                  = Just $ do setContentType $ "text" </> "plain"
45 -- >                              output "Hello, world!"
46 -- >              , resHead   = Nothing
47 -- >              , resPost   = Nothing
48 -- >              , resPut    = Nothing
49 -- >              , resDelete = Nothing
50 -- >              }
51 runHttpd :: Config -> ResTree -> IO ()
52 runHttpd cnf tree
53     = cnf `seq` tree `seq`
54       withSocketsDo $
55       do installHandler sigPIPE Ignore Nothing
56          so <- listenOn (cnfServerPort cnf)
57          loop so
58     where
59       loop :: Socket -> IO ()
60       loop so
61           -- 本當は Network.accept を使ひたいが、このアクションは勝手に
62           -- リモートのIPを逆引きするので、使へない。
63           = so `seq`
64             do (h, addr) <- accept' so
65                tQueue    <- newInteractionQueue
66                readerTID <- forkIO $ requestReader cnf tree h addr tQueue
67                writerTID <- forkIO $ responseWriter cnf h tQueue readerTID
68                loop so
69
70       accept' :: Socket -> IO (Handle, So.SockAddr)
71       accept' soSelf
72           = soSelf `seq`
73             do (soPeer, addr) <- So.accept soSelf
74                hPeer          <- So.socketToHandle soPeer ReadWriteMode
75                return (hPeer, addr)