functions used in defroutes; an arity probem/mystery

96 views
Skip to first unread message

Ryan Waters

unread,
Dec 18, 2013, 10:40:24 AM12/18/13
to comp...@googlegroups.com
Complete code here https://github.com/http-kit/chat-websocket/blob/master/src/main.clj

- - -

If defroutes specifies a response function with no args, how can the definition of that function be arity 1 (the request)?

(defn chat-handler [req]
  (with-channel req channel
    (info channel "connected")
    ...))

(defroutes chartrootm
  (GET "/ws" []  chat-handler)
  (files "" {:root "static"})
  (not-found "<p>Page not found.</p>" ))


When I try that style in my own code I get:
clojure.lang.ArityException: Wrong number of args (0) passed to: views$ws-test
        at clojure.lang.AFn.throwArity(AFn.java:437)
        at clojure.lang.AFn.invoke(AFn.java:35)

Thank you,
Ryan

James Reeves

unread,
Dec 18, 2013, 10:54:17 AM12/18/13
to Compojure
I'm not quite sure what you're asking. What do you mean by "response function with no args"?

- James


--
You received this message because you are subscribed to the Google Groups "Compojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email to compojure+...@googlegroups.com.
To post to this group, send email to comp...@googlegroups.com.
Visit this group at http://groups.google.com/group/compojure.
For more options, visit https://groups.google.com/groups/opt_out.

Ryan Waters

unread,
Dec 18, 2013, 11:14:36 AM12/18/13
to comp...@googlegroups.com, ja...@booleanknot.com
In the link below the function 'chat-handler' is apparently called with no args when someone does a GET on /ws, according to this:

(defroutes chartrootm
  (GET "/ws" []  chat-handler)
  (files "" {:root "static"})
  (not-found "<p>Page not found.</p>" ))

However, the actual function definition requires a single argument, according to this:

(defn chat-handler [req]
  (with-channel req channel
    (info channel "connected")
    ...))

I don't understand how that works.

- Ryan

James Reeves

unread,
Dec 18, 2013, 11:21:44 AM12/18/13
to Ryan Waters, Compojure
Oh! That's because it's not called with no arguments. If it were called with no arguments, the code would look like:

    (GET "/ws" [] (chat-handler))

Instead, the code looks like:

    (GET "/ws" [] chat-handler)

We're not calling the function; we're returning it, in the same way as we'd return a value.

The reason it works is because if a function is returned by a route, it's treated as a handler and called with the current request. In other words, the above code is equivalent to:

    (GET "/ws" req (chat-handler req))

- James

Ryan Waters

unread,
Dec 18, 2013, 11:36:16 AM12/18/13
to comp...@googlegroups.com, Ryan Waters, ja...@booleanknot.com
Ah ha!  Now I understand - thank you for your time!
Reply all
Reply to author
Forward
0 new messages