LoginSignup
4
3

More than 5 years have passed since last update.

Haskell備忘録(cgi作ってみる)

Last updated at Posted at 2014-06-26

すごい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使ってみようかな。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3