【问题标题】:Compojure - map query parameters with string keysCompojure - 使用字符串键映射查询参数
【发布时间】:2017-04-14 02:48:07
【问题描述】:

我知道我可以将 查询字符串 映射为 keyworkd 映射。

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

但是有没有办法对 字符串键映射 做同样的事情? (使用 Compojure 或 Ring

这里的重点不是迭代地图或使用函数,而是默认使用字符串键创建它

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

【问题讨论】:

  • 您使用的是哪个中间件?使用 ring.middleware.params 时,我确实得到了一个字符串键控映射

标签: clojure compojure ring


【解决方案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 "HttpInputOverHTTP@6756d3a3"],
 :scheme :http,
 :request-method :get}

Ring 提供 ring.params.wrap-params 中间件,它解析查询字符串并在 params-key 下创建它的哈希图:

(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"}

【讨论】:

    【解决方案2】:

    不确定组合,但您可以自行撤消:

    (use 'clojure.walk)
    
    (stringify-keys {:a 1 :b {:c {:d 2}}}) 
    ;=> {"a" 1, "b" {"c" {"d" 2}}}
    

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

    【讨论】:

    • 或手动:(defn stringify-keys [m] (->> (seq m) (map #(update % 0 name)) (into {}))),当然不处理嵌套地图。
    • 我已经在使用stringfy-keys。但我认为在创建地图后再次迭代地图效率低下(地图的键已经从创建时的字符串“转换”为关键字)。我想要一个默认使用字符串键创建地图的解决方案。
    猜你喜欢
    • 2011-12-08
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2021-10-26
    • 2012-02-16
    • 2012-04-02
    • 2015-03-17
    • 1970-01-01
    相关资源
    最近更新 更多