如何使用 Noir Web 框架进行 HTTP 302 重定向 [英] How to do HTTP 302 redirects with Noir Web framework

查看:17
本文介绍了如何使用 Noir Web 框架进行 HTTP 302 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在帮助建立一个使用 Clojure 的 Noir 框架的网站,尽管我在 Django/Python 方面有更多的经验.在 Django 中,我习惯使用

I'm helping to set up a Web site with Clojure's Noir framework, though I have a lot more experience with Django/Python. In Django, I'm used to URLs such as

http://site/some/url 

被 302 自动重定向到

being 302-redirected automagically to

http://site/some/url/

黑色更挑剔,不会这样做.

Noir is more picky and does not do this.

自动执行此操作的正确方法是什么?由于良好的 URL 是访问站点的重要方式,而且许多用户会忘记尾部斜杠,因此这是我想添加到我的站点的基本功能.

What would be the proper way to do this automatically? Since good URLs are an important way of addressing into a site, and many users will forget the trailing slash, this is basic functionality I'd like to add to my site.

根据@IvanKoblik 的建议,以下是最终对我有用的方法:

Here is what finally worked for me, based on @IvanKoblik's suggestions:

(defn wrap-slash [handler]
  (fn [{:keys [uri] :as req}]
    (if (and (.endsWith uri "/") (not= uri "/"))
      (handler (assoc req :uri (.substring uri
                                0 (dec (count uri)))))
      (handler req))))

推荐答案

我认为这可以通过自定义中间件实现.noir/server 具有公共功能 add-middleware.

I think this may be possible with a custom middleware. noir/server has public function add-middleware.

这是来自 webnoir 的 页面,解释了如何做到这一点.

Here's a page from webnoir explaining how to do that.

源代码来看自定义中间件首先执行,因此您可以自行处理会话、cookie、url 参数等.

Judging by the source code this custom middleware is executed first, so you'd be on your own in terms of sessions, cookies, url params, etc.

我写了一个非常愚蠢的中间件包装器版本,它检查请求 URI 是否以斜杠结尾,如果不是,则重定向到结尾带有斜杠的 URI:

I wrote a very silly version of the middleware wrapper that checks if request URI ends with slash and if not redirects to URI with slash at the end:

(use [ring.util.response :only [redirect]])

(defn wrap-slash [handler]
  (fn [{:keys [uri] :as req}]
    (if (.endsWith uri "/")
      (handler req)
      (redirect
       (str uri "/")))))

我在我的戒指/胡子网络应用上测试了它,它运行得相当好.

I tested it on my ring/moustache web app and it worked reasonably well.

EDIT1(在您回复我的评论后扩展我的答案.)

EDIT1 (Expanding my answer after your reply to my comment.)

您可以使用自定义中间件来添加或删除尾部斜杠的 URL.只需执行以下操作即可删除尾部斜杠:

You could use custom middleware to either add or strip URL of trailing slash. Just do something like this to strip away trailing slash:

(use [ring.util.response :only [redirect]])

(defn add-slash [handler]
  (fn [{:keys [uri] :as req}]
    (if (.endsWith uri "/")
      (handler (assoc req 
                      :uri (.substring uri 
                                       0 (dec (count uri)))))
      (handler req))))

这篇关于如何使用 Noir Web 框架进行 HTTP 302 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆