clojure で JSONを返すhttpサーバを書く

clojureJSONを返すhttpサーバを書いてみます

プロジェクトを作成する

以下のコマンドでcompojureのテンプレートをつかってプロジェクトを作成します。

lein new compojure api_sample

compojureはRubyでいうSinatraに相当するフレームワークです。 RingというRubyでいうRackをラップして作られています。

サーバーの起動

プロジェクトのディレクトリに移動して、以下のコマンドを実行

lein ring server

JSONかえすぞ

必要なパッケージをいれる

project.cljの依存関係に以下を追記して、lein deps

[ring/ring-core "1.2.0"]
[ring/ring-json "0.2.0"]
; これはサンプルを作成するためだけに必要です
[clj-time "0.8.0"]

ルーティングに追記

src/api_sample/handler.cljのルーティングに現在時刻を返す記述を追記して、レスポンスの形式をJSONにするようにします。こんなかんじ

(ns api_sample.handler
  (:require [compojure.core :refer :all]
            [compojure.handler :as handler]
            [compojure.route :as route]
            [ring.util.response :refer [resource-response response]]
            [ring.middleware.json :as middleware]
            [clj-time.local :as tl]
            [clj-time.format :as tf]))

(defn current_time []
  (tf/unparse (tf/formatter-local "kk:mm:ss") (tl/local-now)))
(println (current_time))

(defroutes app-routes
  (GET "/" [] "Hello World")
  (POST "/time/current" []
        (response {:value (current_time)}))
  (route/resources "/")
  (route/not-found "Not Found"))

(def app
  (-> (handler/site app-routes)
      (middleware/wrap-json-body)
      (middleware/wrap-json-response)))

ためす

usr0600298: curl -XPOST http://localhost:3001/time/current
{"value":"16:35:01"}%

よっしゃ

コメント

HTMLの生成とかもしたいんですけど、内部DSL感が半端無くて... ( weavejester/hiccup · GitHub )