すごいH本を途中まで読み進め、HaskellをWebで使ってみる。
簡単なcgiを作成。
環境はSL 6.5、ghc 7.0.4。
index.cgi.hs
import Network.CGI
inputForm :: String -> String
inputForm script = concat [
"<form action=\"", script, "\" method=\"GET\">\n",
" <p>What your name?</p>\n",
" <input type=\"text\" name=\"name\">\n",
" <input type=\"submit\" value=\"send\">\n",
"</form>\n"]
putName :: String -> String
putName name = concat ["<h3>Hello, ", name, "!</h3>"]
body :: Maybe String -> String -> String
body name script =
case name of
Just x -> putName x
Nothing -> inputForm script
html :: Maybe String -> String -> String
html name script = concat [
"<!DOCTYPE html>\n",
"<html>\n",
"<head>\n",
"<meta charset=\"UTF-8\">\n",
"<title>Hello</title>\n",
"<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">\n",
"<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">\n",
"<meta name=\"format-detection\" content=\"telephone=no\">\n",
"<meta name=\"viewport\" content=\"width=device-width, minimum-scale=1.0, maximum-scale=0.6667, user-scalable=no\">\n",
"<meta name=\"robots\" content=\"noindex,nofollow\">\n",
"</head>\n",
"<body>\n",
body name script,
"</body>\n",
"</html>"]
cgiMain :: CGI CGIResult
cgiMain = do
setHeader "Content-type" "text/html; charset=UTF-8"
script <- scriptName
name <- getInput "name"
output $ html name script
main :: IO ()
main = runCGI $ handleErrors cgiMain
コンパイルする。
ghc -o index.cgi index.cgi.hs
Haskellの作法に沿ってないと思うけど、とりあえず動いた。
以下のURLを参考にさせて頂きました、というかパクっ・・・有り難う御座います。
http://d.hatena.ne.jp/shunsuk/20090803/1249300625
次はhamlet使ってみようかな。