使用 Compojure,除了必须格式化请求 URL 之外,还有其他方法可以重定向到已定义的路由之一吗?
例如,在以下简化的 defroutes
声明中:
(defroutes app-routes
; ...
(GET "/something-that-may-redirect" [query-param]
; parse `query-param` into `arg1` and `arg2` and:
(ring.util.response/redirect (format "/another-route?param1=%s¶m2=%s" arg1 arg2))
(GET "/another-route" [param1 param2] ...)
; ...
在这里,我必须格式化要重定向到的 URL(通常还处理转义),以便稍后由 Compojure 本身解析该 URL 并提取回 param1
和参数2
。
所以问题是,是否有一种方法可以重定向并让 Compojure 格式化请求 URL,并知道它已经具有有关参数的信息?就像简单的事情:
(redirect "/another-route" arg1 arg2)
它将把 URL itlsef 格式化为:
"/another-route?param1=[value of arg1]¶m2=[value of arg2]"
附注这个想法本身当然并不新鲜。其他一些 Web 框架也具有类似的功能 - 例如,对于 Python 的 Flask Web 框架,可以使用 url_for根据基本路径和查询参数值创建格式良好且转义的 URL:
# for example, in Python's Flask framework
url_for('route-name', param1='value1', param2='value2')
最佳答案
我相信这是一个重复的问题How to convert map to URL query string in Clojure/Compojure/Ring?
此代码将实现发帖人寻求的目标。
(defroutes app-routes
(GET "/something-that-may-redirect" [arg1 arg2]
(redirect (str "/another-route" "?" (ring.util.codec/form-encode {:param1 arg1 :param2 arg2}))))
(GET "/another-route" response (str response)))
关于clojure - Compojure - 使用重定向时避免 "manual"URL 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33270442/