2016-11-29 37 views
0

我知道我可以将查询字符串映射为keyworkd映射。Compojure - 使用字符串键映射查询参数

(defroutes my-routes 
    (GET "/" {params :query-params} params)) 

但是,有没有办法做一个字符串加密映射一样吗? (使用的Compojure或环

这里的关键是不要重复在地图上或使用功能,但默认具有字符串键创建它。

{ :a "b" } -> {"a" "b"} 
+0

这你使用的是中间件吗?当使用'ring.middleware.params' –

回答

1

的Compojure 1.5.1不解析默认任何查询字符串(不使用任何中间件) 。但是,这在早期版本中可能会有所不同。

(require '[compojure.core :refer :all]) 
(require '[clojure.pprint :refer [pprint]]) 

(defroutes handler 
    (GET "/" x 
     (with-out-str (pprint x)))) ;; just a way to receive a pretty printed string response 

$ curl localhost:3000/?a=b 
{:ssl-client-cert nil, 
:protocol "HTTP/1.1", 
:remote-addr "127.0.0.1", 
:params {}, ;; EMPTY! 
:route-params {}, 
:headers 
{"user-agent" "curl/7.47.1", "accept" "*/*", "host" "localhost:3000"}, 
:server-port 3000, 
:content-length nil, 
:compojure/route [:get "/"], 
:content-type nil, 
:character-encoding nil, 
:uri "/", 
:server-name "localhost", 
:query-string "a=b", ;; UNPARSED QUERY STRING 
:body 
#object[org.eclipse.jetty.server.HttpInputOverHTTP 0x6756d3a3 "[email protected]"], 
:scheme :http, 
:request-method :get} 

环提供ring.params.wrap-params中间件,它在解析查询字符串,并创建它的下一个HashMap PARAMS键:

(defroutes handler 
    (wrap-params (GET "/" x 
       (prn-str (:params x))))) 

$ curl localhost:3000/?a=55 
{"a" "55"} 

Additionaly ring.params.wrap-params可用于:

(defroutes handler 
    (wrap-params (wrap-keyword-params (GET "/" x 
            (prn-str (:params x)))))) 

$ curl localhost:3000/?a=55 
{:a "55"} 
0

不确定的Compojure,但可以自行撤消:

(use 'clojure.walk) 

(stringify-keys {:a 1 :b {:c {:d 2}}}) 
;=> {"a" 1, "b" {"c" {"d" 2}}} 

https://clojuredocs.org/clojure.walk/stringify-keys

+0

或手动操作时,我会得到一个字符串键图:'(defn stringify-keys [m]( - >>(seq m)(map#(update%0 name))(into {})))',当然不会处理嵌套的地图。 –

+0

我已经在使用'stringfy-keys'。但是我认为在创建地图后再次迭代地图效率不高(地图的键已经从创建时的字符串“转换”为关键字)。我想要一个解决方案,默认情况下用字符串键创建地图。 –

相关问题