簡易HTTP Server
30分プログラム、その362。http://www.haskell.org/ghc/docs/latest/html/libraries/network/Network-Socket.htmlを使って、簡易HTTPサーバを書いてみた。
これだけ、IO aが多いとHaskell使ってる意味がほとんどない気がするけどね。
ソースコード
import Network.Socket server action = do sock <- socket AF_INET Stream 0 addr <- inet_addr "127.0.0.1" bindSocket sock $ SockAddrInet 8080 addr listen sock 1 sequence_ $ repeat $ loop sock where loop sock = do (client,_) <- accept sock action client sClose client return () recvAll sock block = do (buf,readed) <- recvLen sock block if readed == block then return buf else do rest <- recvAll sock block return $ buf ++ rest httpServer = server http where http client = do s <- recv client 1024 putStrLn s send client "HTTP/1.x 200 OK\n" send client "Content-type: text/html\n" send client "\n" send client "<h1>Hello, world!</h1>\n"