Clojure プログラミングでコードのスニペットに出くわしましたが、バグがありました。私は Clojure の初心者で、バグがコードのどこにあるのかわかりません。
(ns ring-tutorial.core
(:require [compojure.handler :as ch]
[compojure.core :refer [GET PUT POST defroutes]]
[compojure.route :as cr]
[ring.util.response :as response]))
(def ^:private counter (atom 0))
(def ^:private mappings (ref {}))
(defn url-for
[id]
(@mappings id))
(defn shorten!
"Stores the given URL under a new unique identifier and returns it as a string."
([url]
(let [id (swap! counter inc)
id (Long/toString id 36)] ;;convert to base 36 string
(or (shorten! url id)
(recur url))))
([url id] ;;url is provided with an id.
(dosync
(when-not (@mappings id)
(alter mappings assoc id url)
id))))
(defn retain
[& [url id :as args]]
(if-let [id (apply shorten! args)]
{:status 201
:headers {"Location" id}
:body (list "URL " url " assigned the short identifier " id " \n")}
{:status 409 :body (format "Short URL %s is already taken \n " id)}))
(defn redirect
[id]
(if-let [url (url-for id)]
(ring.util.response/redirect url) ;;Appropriately redirect the URL based on ethe ID.
{:status 404 :body (str "No such short URL: \n" id)})) ;;Return a 404 if no URL for the particular ID found.
(defroutes app*
(GET "/" request "Hello World!")
(PUT "/:id" [id url] (retain url id))
(POST "/" [url ] (retain url))
(GET "/:id" [id] (redirect id))
(GET "/list/" [] (interpose "\n" (keys @mappings)))
(cr/not-found "Its a 404!\n"))
(def app (ch/api #'app*))
$ CURL -X POST 'localhost:8080/?url= http://www.yahoo.com/ ' を実行すると、コマンドを再実行すると、URL に識別子 1 が与えられ、'URL に識別子 2 が与えられましたただし、yahoo.com には既に識別子 1 があるというエラーが表示されるはずです。
これは私が見ることができるバグです。機能しますが、修正できていません。
ありがとう!