4 import Network
.HTTP
.Stream
8 import Control
.Category
9 import Prelude
hiding (id,(.))
10 import Text
.XHtml
.Transitional
11 import Control
.Concurrent
14 getHogVersion
= "0.1.0"
15 getFullName
= getHogName
++ " " ++ getHogVersion
18 = AF_UNSPEC
-- unspecified
20 deriving (Eq
, Ord
, Read, Show)
22 type RequestHandler
= Request
String -> IO (Response
String)
24 --main = runHttpServer defaultIndexDoc
25 main
= runHttpServer hellowWorldHandler
27 hellowWorldHandler
:: RequestHandler
28 hellowWorldHandler _
=
29 return $ successResponse
$ prettyHtml helloWorldDoc
31 successResponse
:: String -> Response
String
33 Response
(2,0,0) "" [] s
37 header
<< thetitle
<< (getFullName
++ " running!")
38 Text
.XHtml
.Transitional
.+++
39 body
<< h1
<< (getFullName
++ " running!")
41 --defaultIndexDoc :: Html
42 --defaultIndexDoc = hopReadFile "/var/www/index.html" >>= return . stringToHtml
44 -- c <- hopReadFile "/var/www/index.html"
45 -- return $ stringToHtml liftM c
47 hopReadFile
:: String -> IO String
48 hopReadFile filename
= readFile filename
50 runHttpServer
:: RequestHandler
-> IO ()
53 sock
<- socket AF_LANA Stream
0
54 setSocketOption sock ReuseAddr
1
55 bindSocket sock
$ SockAddrInet
8080 iNADDR_ANY
57 forever
$ acceptConnection sock
$ handleHttpConnection r
59 acceptConnection
:: Socket
-> (Handle -> IO ()) -> IO ()
60 acceptConnection s k
=
61 Network
.accept s
>>= \(h
,_
,_
) -> forkIO
(k h
) >> return ()
63 instance Stream
Handle where
64 readLine h
= hGetLine h
>>= \ l
-> return $ Right
(l
++ "\n")
65 readBlock h n
= replicateM n
(hGetChar h
) >>= return . Right
66 writeBlock h s
= mapM_ (hPutChar h
) s
>>= return . Right
69 handleHttpConnection
:: RequestHandler
-> Handle -> IO ()
70 handleHttpConnection r c
=
72 (receiveRequest
>>> handleRequest r
>>> handleResponse
) c
>>
73 Network
.HTTP
.Stream
.close c
75 receiveRequest
= Kleisli Network
.HTTP
.Stream
.receiveHTTP
76 handleRequest r
= right
(Kleisli r
)
77 handleResponse
= Kleisli
(print ||| Network
.HTTP
.Stream
.respondHTTP c
)