用Clojure编写REST service 二 Noir创建Rest API
来源:互联网 发布:乌云整站源码 编辑:程序博客网 时间:2024/05/21 17:39
前面一节介绍了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 allowsyou 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/
- 用Clojure编写REST service 二 Noir创建Rest API
- 用Clojure编写REST service 一 Noir创建web app
- 用Clojure编写REST service 三 返回JSON
- 用Clojure编写REST service 四 读取配置文件
- 用Clojure编写REST service 五 使用logback(有bug)
- 用Clojure编写REST service 六 使用log4j
- 用Clojure编写REST service 七 启动时读取配置文件
- subversionedge rest api编写
- rest api的编写
- 用PHP创建一个REST APi
- 编写合格的REST API
- 创建一个WCF Rest Service
- 使用ASP.NET web API创建REST服务(二)
- 自己创建一个Rest API
- spring mvc 创建 rest api
- 使用SpringMVC 创建REST API
- rest service
- Eclipse+Tomcat+Jersey 编写 REST web service
- javascript
- windows7下 php+mysql+apache+phpm…
- 如何在IOS中使用block
- 怎样将Oracle一张表的多个字段更新到另一张表中去
- JAVA实现简易计算器
- 用Clojure编写REST service 二 Noir创建Rest API
- centos 中文输入法
- 局部变量与函数返回地址
- poj 1015 陪审团
- 参考文献格式自动生成器
- 【Boost】boost::algorithm的几个简单例子
- UML结构
- 程序员的精神
- LPARAM转换成CString出现乱码现象