How to redirect HTTP 302 with a Noir Web network

I help create a website with the Clojure Noir framework, although I have much more experience with Django / Python. In Django, I'm used to URLs like

http://site/some/url 

302 is automatically redirected to

 http://site/some/url/ 

Noir is more picky and does not.

What would be the right way to do this automatically? Since good URLs are an important way to address a site, and many users will forget the end slash, this is the basic functionality that I would like to add to my site.

EDIT: here is what finally worked for me based on @IvanKoblik 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)))) 
+6
source share
2 answers

I think this is possible with the help of special middleware. noir / server has a public add-middleware function.

Here is a page from webnoir explaining how to do this.

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


I wrote a very silly version of the middleware shell that checks to see if the request completed the URI with a slash, and if it does not redirect the URI with a 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 dialer / mustache web application and it worked pretty well.


EDIT1 (Extension of response after responding to my comment.)

You can use specialized middleware to add or remove a trailing slash URL. Just do something like this to undo the 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)))) 
+2
source

I found this useful:

 (defpage "" [] (response/redirect "/myapp/")) 

/ myapp → / myapp /

+1
source

Source: https://habr.com/ru/post/925624/


All Articles