2013-04-05 75 views
5

我正在關注使用ring和jetty在Clojure中創建簡單Web服務的this example如何在Clojure中使用Ring運行Jetty示例

我有這個在我的project.clj:

(defproject ws-example "0.0.1" 
    :description "REST datastore interface." 
    :dependencies 
    [[org.clojure/clojure "1.5.1"] 
    [ring/ring-jetty-adapter "0.2.5"] 
    [ring-json-params "0.1.0"] 
    [compojure "0.4.0"] 
    [clj-json "0.5.3"]] 
    :dev-dependencies 
    [[lein-run "1.0.0-SNAPSHOT"]]) 

這在腳本/ run.clj

(use 'ring.adapter.jetty) 
(require '[ws-example.web :as web]) 

(run-jetty #'web/app {:port 8080}) 

這將src/ws_example/web.clj

(ns ws-example.web 
    (:use compojure.core) 
    (:use ring.middleware.json-params) 
    (:require [clj-json.core :as json])) 

(defn json-response [data & [status]] 
    {:status (or status 200) 
    :headers {"Content-Type" "application/json"} 
    :body (json/generate-string data)}) 

(defroutes handler 
    (GET "/" [] 
    (json-response {"hello" "world"})) 

    (PUT "/" [name] 
    (json-response {"hello" name}))) 

(def app 
    (-> handler 
    wrap-json-params)) 

但是,當我執行時:

lein run script/run.clj 

我得到這個錯誤:

No :main namespace specified in project.clj. 

爲什麼會出現這個?如何解決?

+0

您鏈接的教程使用Leiningen 1.x - 您應該使用lein2。 – Alex 2013-04-05 17:29:44

+0

如果我能找到一個自從學習以來就能工作的教程,那將是非常棒的。有什麼建議麼?我想在Clojure – 2013-04-05 17:33:38

回答

2

你必須把那(run-jetty)東西成-main的地方,然後把它添加到project.clj

:main ws-example.core) 
+0

中創建一個Web服務謝謝,你有關於某處的建議嗎? run-jetty的東西位於一個名爲run.clj的腳本中。 – 2013-04-05 17:22:39

0

lein help run

USAGE: lein run -m NAMESPACE[/MAIN_FUNCTION] [ARGS...] 
Calls the main function in the specified namespace. 

所以,你需要把你的script.clj某處在項目源路徑上,然後將其稱爲:

lein run -m script 
+0

這是使用lein2。在lex run中的命令在1.x中略有不同。 – Alex 2013-04-05 17:31:16

3

由於lein run(根據lein help run)的目的是「運行項目的主函數」,所以出現此錯誤。您的ws-example.web命名空間中沒有-main函數,您的project.clj文件中也沒有指定:main,這是lein run所抱怨的內容。

要解決這個問題,你有幾個選擇。您可以將run-jetty代碼移至ws-example.web函數的新-main函數,然後再說lein run -m ws-example.web。或者你可以這樣做,也可以添加一行:main ws-example.webproject.clj,然後再說lein run。或者您可以嘗試使用lein exec plugin來執行文件,而不是命名空間。

欲瞭解更多信息,請查看Leiningen Tutorial