用Clojure编写REST service 四 读取配置文件

来源:互联网 发布:关于数据分析的论文 编辑:程序博客网 时间:2024/05/16 16:04

最好的配置文件写法是采用clj文件,下面先把前面的a.xml文件改成a.clj文件,内容如下:

{:mongodb "localhost" :listen_port 7777 :login_timeout 200 :check_timeout 200}
这里定义了一个map。注意,localhost是字符串,必须用双引号。

这里用空格分开每个key/value组成的pair.

在test.clj文件中添加一行代码:

(ns my-website.rest.test  (:require [noir.response :as response])  (:use [noir.core :only [defpage]]))(defpage "/rest/:id" {:keys [id]} (response/json {:userId id}))(defpage "/rest/file/:name" {:keys [name]} (str (load-file (str "/opt/" name))))
最后一行允许输入文件名,然后读取/opt/下的该文件内容,并以字符串形式返回到客户端。

在浏览器上输入网址:http://localhost:8080/rest/file/a.clj

返回结果是:

{:mongodb "localhost", :check_timeout 200, :listen_port 7777, :login_timeout 200}

注意,自动添加了,作为分隔符号。

继续改进,我希望能够在web service请求中读取配置文件a.clj,然后取出mongodb 主机ip,

修改代码如下:

(ns my-website.rest.test  (:require [noir.response :as response])  (:use [noir.core :only [defpage]]))(defpage "/rest/:id" {:keys [id]} (response/json {:userId id}))(def load_config (fn [name] (load-file (str "/opt/" name))))(def host   (fn [name] (:mongodb (load_config name))))(defpage "/rest/file/:name" {:keys [name]} (str "mongodb host: " (host name)                                            ))

请求结果变成:

mongodb host: localhost

具体fn的用法参考我的文章:

http://blog.csdn.net/sheismylife/article/details/8457872



原创粉丝点击