clojure - Compojure - 使用重定向时避免 "manual"URL 格式

标签 clojure compojure ring

使用 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&param2=%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]&param2=[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/

相关文章:

clojure - 如何在ring init函数中获取ServletContext

string - "Simple String template replacement in Scala and Clojure"的后续

clojure - 从 Compojure 提供静态文件

clojure - 没有码头的环/组合

clojure - 使用自定义 :store with wrap-multipart-params in ring middle ware

clojure - 无法从 compojure 中的 POST 请求中提取多部分参数

java - Lein 无法将 jar 添加到 uberjar

clojure - 为什么我不能在 js->clj 生成的序列中调用 seq 函数?

python - Clojure - 进行动态嵌套循环的惯用方法

clojure - 运行服务器时注册多个处理程序