【问题标题】:How to Run Jetty Example with Ring in Clojure如何在 Clojure 中使用 Ring 运行 Jetty 示例
【发布时间】:2013-04-05 16:26:35
【问题描述】:

我正在关注 this example 在 Clojure 中使用 ring 和 jetty 创建一个简单的 Web 服务。

我的 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。
  • 如果我能找到一个自学习以来就有效的教程,那就太好了。有什么建议么?我想在 Clojure 中创建一个 Web 服务

标签: clojure jetty leiningen ring


【解决方案1】:

您收到此错误是因为 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 plugin 来执行文件,而不是命名空间。

欲了解更多信息,请查看Leiningen Tutorial

【讨论】:

    【解决方案2】:

    您必须将 (run-jetty) 的内容放入 -main 某处,然后将其添加到 project.clj

    :main ws-example.core)
    

    【讨论】:

    • 谢谢,您对某个地方有什么建议吗? run-jetty 的东西位于一个名为 run.clj 的脚本中。
    【解决方案3】:

    来自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。 lein run 的命令在 1.x 中略有不同。
    猜你喜欢
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 2020-11-15
    • 1970-01-01
    • 2014-04-17
    • 2015-02-15
    相关资源
    最近更新 更多