I'm trying to follow the tutorial on the Racket guide on simple web apps, but can't get one, basic, basic thing.
How can you have a servlet serve different content based on the request URL? Despite my scouring, even the huge blog example was one big file and everything handled with huge get query strings behind my back. How can I do anything based on URLs? Clojure's Noir framework puts this basic feature big up front on the home page (defpage
) but how to do this with Racket?
The URL is part of the
request
structure that the servlet receives as an argument. You can get the URL by callingrequest-uri
, then you can look at it to do whatever you want. The request also includes the HTTP method, headers, and so on.But that's pretty low-level. A better solution is to use
dispatch-rules
to define a mapping from URL patterns to handler functions. Here's an example from the docs:Make your main servlet handler
blog-dispatch
. The URLhttp://yoursite.com/
will be handled by calling(list-posts req)
, wherereq
is the request structure. The URLhttp://yoursite.com/posts/a-funny-story
will be handled by calling(review-post req "a-funny-story")
. And so on.