]> gitweb @ CieloNegro.org - Lucu.git/blob - Network/HTTP/Lucu/Httpd.hs
Optimized as possible as I can.
[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 @installHandler sigPIPE Ignore Nothing@. This can hardly
25 -- cause a problem but it may do.
26 --
27 -- Example:
28 --
29 -- > module Main where
30 -- > import Network.HTTP.Lucu
31 -- > 
32 -- > main :: IO ()
33 -- > main = let config    = defaultConfig
34 -- >            resources = mkResTree [ ([], helloWorld) ]
35 -- >        in
36 -- >          runHttpd config resourcees
37 -- >
38 -- > helloWorld :: ResourceDef
39 -- > helloWorld = ResourceDef {
40 -- >                resUsesNativeThread = False
41 -- >              , resIsGreedy         = False
42 -- >              , resGet
43 -- >                  = Just $ do setContentType $ "text" </> "plain"
44 -- >                              output "Hello, world!"
45 -- >              , resHead   = Nothing
46 -- >              , resPost   = Nothing
47 -- >              , resPut    = Nothing
48 -- >              , resDelete = Nothing
49 -- >              }
50 runHttpd :: Config -> ResTree -> IO ()
51 runHttpd cnf tree
52     = cnf `seq` tree `seq`
53       withSocketsDo $
54       do installHandler sigPIPE Ignore Nothing
55          so <- listenOn (cnfServerPort cnf)
56          loop so
57     where
58       loop :: Socket -> IO ()
59       loop so
60           -- 本當は Network.accept を使ひたいが、このアクションは勝手に
61           -- リモートのIPを逆引きするので、使へない。
62           = so `seq`
63             do (h, addr) <- accept' so
64                tQueue    <- newInteractionQueue
65                readerTID <- forkIO $ requestReader cnf tree h addr tQueue
66                writerTID <- forkIO $ responseWriter cnf h tQueue readerTID
67                loop so
68
69       accept' :: Socket -> IO (Handle, So.SockAddr)
70       accept' soSelf
71           = soSelf `seq`
72             do (soPeer, addr) <- So.accept soSelf
73                hPeer          <- So.socketToHandle soPeer ReadWriteMode
74                return (hPeer, addr)