如何在Clojure中使用Ring运行Jetty示例

6
我可以帮您翻译成中文。这段内容是关于使用ring和jetty在Clojure中创建简单网络服务的示例,您正在跟随此示例进行学习。
以下是我的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"]])

这是在 script/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.

为什么我会得到这个错误,如何解决?


你链接的教程使用的是Leiningen 1.x - 你应该使用lein2。 - Alex
有没有什么好的建议?我正在学习,如果能找到一个有效的教程就太好了。我想在Clojure中创建一个Web服务。 - David Williams
3个回答

3
您会收到此错误是因为lein run的目的(根据lein help run)是“运行项目的-main函数。” 您的ws-example.web命名空间中没有-main函数,也没有在您的project.clj文件中指定:main,这就是lein run抱怨的原因。
要解决此问题,您有几个选项。 您可以将run-jetty代码移到ws-example.web函数的新-main函数中,然后说lein run -m ws-example.web。 或者您可以这样做,还可以在project.clj中添加一行:main ws-example.web,然后只需说lein run。 或者您可以尝试使用lein exec插件来执行文件,而不是命名空间。
要了解更多信息,请查看Leiningen教程

2

您需要将(run-jetty)的代码放在某个-main中,并将其添加到project.clj中,如下所示:

:main ws-example.core)

谢谢,你有关于“某处”的建议吗?run-jetty的东西位于一个名为run.clj的脚本中。 - David Williams

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

这是使用lein2。在1.x中,“lein run”命令略有不同。 - Alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接