如何解析在Clojure中的URL参数? [英] How to parse URL parameters in Clojure?
问题描述
如果我有请求size = 3& mean = 1& sd = 3& type = pdf& distr = normal
(defn request-> map [request] ...)
接受此请求,
返回映射 {:size 3, :mean 1,:sd 3,:type pdf,:distr normal}
这里是我的尝试(使用clojure.walk和clojure。 string):
(defn request-to-map
[request]
(keywordize-keys
(apply hash-map
(split request#(& | =)))))
我对其他人如何解决这个问题很感兴趣。
Java库的数量。除非我仔细阅读URI规范,并确保没有丢失任何边缘情况(例如,在查询中出现两次不同值的参数),否则我会犹豫要尝试滚动我自己的解析器。这使用 jetty-util : / p>
(import'[org.eclipse.jetty.util UrlEncoded MultiMap])
(defn parse- query-string [query]
(let [params(MultiMap。)]
(UrlEncoded / decodeTo query paramsUTF-8)
(into {} params)))
user> (parse-query-stringsize = 3& mean = 1& sd = 3& type = pdf& distr = normal)
{sd3,mean normal,typepdf,size3}
If I have the request "size=3&mean=1&sd=3&type=pdf&distr=normal"
what's the idiomatic way of writing the function (defn request->map [request] ...)
that takes this request and
returns a map {:size 3, :mean 1, :sd 3, :type pdf, :distr normal}
Here is my attempt (using clojure.walk and clojure.string):
(defn request-to-map
[request]
(keywordize-keys
(apply hash-map
(split request #"(&|=)"))))
I am interested in how others would solve this problem.
You can do this easily with a number of Java libraries. I'd be hesitant to try to roll my own parser unless I read the URI specs carefully and made sure I wasn't missing any edge cases (e.g. params appearing in the query twice with different values). This uses jetty-util:
(import '[org.eclipse.jetty.util UrlEncoded MultiMap])
(defn parse-query-string [query]
(let [params (MultiMap.)]
(UrlEncoded/decodeTo query params "UTF-8")
(into {} params)))
user> (parse-query-string "size=3&mean=1&sd=3&type=pdf&distr=normal")
{"sd" "3", "mean" "1", "distr" "normal", "type" "pdf", "size" "3"}
这篇关于如何解析在Clojure中的URL参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!