Compojure - 使用字符串键映射查询参数
Compojure - map query parameters with string keys
我知道我可以将 查询字符串 映射为 keyworkd 映射。
(defroutes my-routes
(GET "/" {params :query-params} params))
但是有没有办法对 字符串键控映射 做同样的事情?
(使用 Compojure 或 Ring)
这里的重点不是遍历映射或使用函数,而是默认使用字符串键创建它。
{ :a "b" } -> {"a" "b"}
不确定compojure,但你可以自己撤消:
(use 'clojure.walk)
(stringify-keys {:a 1 :b {:c {:d 2}}})
;=> {"a" 1, "b" {"c" {"d" 2}}}
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 "HttpInputOverHTTP@6756d3a3"],
:scheme :http,
:request-method :get}
Ring 提供 ring.params.wrap-params
中间件,它解析查询字符串并在参数键下创建它的哈希图:
(defroutes handler
(wrap-params (GET "/" x
(prn-str (:params x)))))
$ curl localhost:3000/?a=55
{"a" "55"}
另外ring.params.wrap-params
可以使用:
(defroutes handler
(wrap-params (wrap-keyword-params (GET "/" x
(prn-str (:params x))))))
$ curl localhost:3000/?a=55
{:a "55"}
我知道我可以将 查询字符串 映射为 keyworkd 映射。
(defroutes my-routes
(GET "/" {params :query-params} params))
但是有没有办法对 字符串键控映射 做同样的事情? (使用 Compojure 或 Ring)
这里的重点不是遍历映射或使用函数,而是默认使用字符串键创建它。
{ :a "b" } -> {"a" "b"}
不确定compojure,但你可以自己撤消:
(use 'clojure.walk)
(stringify-keys {:a 1 :b {:c {:d 2}}})
;=> {"a" 1, "b" {"c" {"d" 2}}}
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 "HttpInputOverHTTP@6756d3a3"],
:scheme :http,
:request-method :get}
Ring 提供 ring.params.wrap-params
中间件,它解析查询字符串并在参数键下创建它的哈希图:
(defroutes handler
(wrap-params (GET "/" x
(prn-str (:params x)))))
$ curl localhost:3000/?a=55
{"a" "55"}
另外ring.params.wrap-params
可以使用:
(defroutes handler
(wrap-params (wrap-keyword-params (GET "/" x
(prn-str (:params x))))))
$ curl localhost:3000/?a=55
{:a "55"}