现在的位置: 首页 > 综合 > 正文

用Clojure编写REST service 二 Noir创建Rest API

2013年04月27日 ⁄ 综合 ⁄ 共 1679字 ⁄ 字号 评论关闭

前面一节介绍了Noir如何非常方便的创建一个web app,但是我的实际一个项目的需求中只需要REST API开发,页面部分都交给了html和Javascript,并不需要Noir在后台渲染网页。

同样无需重新启动程序,在src目录下创建rest目录,里面有一个test.clj文件:

$ tree
.
├── models
├── rest
│   └── test.clj
├── server.clj
└── views
    ├── common.clj
    └── welcome.clj

test.clj文件内容如下:

(ns my-website.rest.test
  (:require [my-website.views.common :as common]
            [noir.content.getting-started])
  (:use [noir.core :only [defpage]]))

(defpage "/rest/get" []
         (common/layout
           [:p "get"]))

同时在serer.clj文件中添加一行:

(server/load-views-ns 'my-website.rest.test)

注意namespace my-website.rest.test中rest对应rest目录,test对应test.clj文件。

然后通过浏览器访问http://localhost:8080/rest/get

可以看到返回的是get字符串。这个最简单的rest api已经有了。

defpage宏定义了URL的路由,默认是处理http get请求的。

文档参考:http://www.webnoir.org/autodoc/1.3.0/noir.core.html#var-defpage

(defpage & args)
Adds a route to the server whose content is the the result of evaluating the body.
The function created is passed the params of the request and the destruct param allows
you to destructure that meaningfully for use in the body.

There are several supported forms:

(defpage "/foo/:id" {id :id})  an unnamed route
(defpage [:post "/foo/:id"] {id :id}) a route that responds to POST
(defpage foo "/foo:id" {id :id}) a named route
(defpage foo [:post "/foo/:id"] {id :id})

The default method is GET.

由于我们不需要渲染网页,现在简化一下test.clj文件的代码:

(ns my-website.rest.test
  (:require [noir.content.getting-started])
  (:use [noir.core :only [defpage]]))

(defpage "/rest/get" [] "get")

现在,去掉了views.common的使用。解释:

1. 第一个参数"/rest/get" 是这个rest api的URL

2. 第二个参数 [ ] 是http 请求的参数,这里暂时没有使用

3. 第三个参数"get"是http response的响应内容 

现在演示一下如何获得http get请求的参数,比如浏览器输入:http://localhost:8080/rest/freebird

freebird就是参数,修改test.clj代码如下:

(defpage "/rest/:id" {:keys [id]} (str "user id: " id))

第二个参数将第一个参数的:id绑定到id上,

第三个参数使用id的值组成response的字符串。

最后返回:

user id: freebird

也可以很方便的处理post请求,具体参考文档:

http://www.webnoir.org/tutorials/routes/

抱歉!评论已关闭.