Sphereとともに

scalaとかplayframeworkとか。技術ブログにしたいなと。環境は Windows7x64, mac です。たまに声優さん情報が混ざります。最近ちょっとClojure触りました。

Clojure その25 Webアプリケーションその1

・・・CSVとかもういいわ(諦め

ClojureでWebアプリケーションつくるには

http://qiita.com/snufkon/items/5224ecc090a8fddd45cd

を見ると、CompojureとHiccup使えばなんとかなりそう

なので手を出してみる

プロジェクトの作成は

lein new compojure [プロジェクト名]

サーバー起動は

lein ring server

以下、ソースコード内コメントに説明を残してあります。

(ns hello-compojure.handler
  (:use compojure.core
        hiccup.core
        hiccup.form
        hiccup.page)
  (:require [compojure.handler :as handler]
            [compojure.route :as route]))

(defn authenticate [id password]
  "Authentication id and password"
  (if (and (= id "admin") (= password "pass"))
    true
    false)) 

(defroutes app-routes
  (GET "/" [] "Hello World")
  ; :id [id] としてやると id の値を受けたurlとなる
  (GET "/:id" [id]
       (html5 
        [:body
        (form-to[:GET "/user/test"]
                (label "id" "id")
                (text-field "id")
                [:br]
                (label "password" "password")
                (password-field "password")
                [:br]
                (submit-button "submit"))]))
  ; text-field "id" や "password" とした部分を引数として渡される。
  ; 引数も text-field に合ったもの(つまりここでは [id password] )になっていないと値を受け取れないみたい。
  (GET "/user/test" [id password]
       (if (= true (authenticate id password))
         (str "success")
         (str "failed")))
  (route/resources "/")
  (route/not-found "Not Found"))

(def app
  (handler/site app-routes))

プログラミングClojure 第2版

プログラミングClojure 第2版