clj-commons / aleph

Asynchronous streaming communication for Clojure - web server, web client, and raw TCP/UDP
http://aleph.io
MIT License
2.54k stars 241 forks source link

How do I redirect a route? #600

Closed wbehrens-on-gh closed 2 years ago

wbehrens-on-gh commented 2 years ago

I'm using compojure with aleph and I was wondering how I could redirect a route?

when using plain ring I'd just use ring's (redirect) function but I can't seem to find an equivalent in aleph?

(defroutes app
  (GET "/" [] (redirect "/home"))
  (GET "/home" [] (views/home))
  (routes/resources "/")
  (routes/not-found "<h1>Page not found</h1>"))

(defn -main []
  (println "Starting server!")
  (http/start-server app {:port 8080})
arnaudgeiser commented 2 years ago

Hello William!

There is no redirect function available out of the box in Aleph. Under the hood, it's just a Location header sent through HTTP. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location

Here is an example if you want to write your own:

(defn redirect [uri]
  {:status 302
   :headers {"Location" uri}})

(defn handler [{:keys [uri]}]
  (case uri
      "/" (redirect "/hello")
      "/hello" {:body "Hello!"}))

(http/start-server
  handler
  {:port 9999})
curl -L localhost:9999                                                                                                                                                                                                                        ✔  2 task  at 18:20:11   
Hello!%  

Hope this helps!

arnaudgeiser commented 2 years ago

Anyway, you can leverage the redirect function from ring.util.response which should still work.