How to show different content based on the path in

2019-04-09 13:27发布

问题:

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?

回答1:

The URL is part of the request structure that the servlet receives as an argument. You can get the URL by calling request-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:

(define-values (blog-dispatch blog-url)
  (dispatch-rules
   [("") list-posts]
   [("posts" (string-arg)) review-post]
   [("archive" (integer-arg) (integer-arg)) review-archive]
   [else list-posts]))

Make your main servlet handler blog-dispatch. The URL http://yoursite.com/ will be handled by calling (list-posts req), where req is the request structure. The URL http://yoursite.com/posts/a-funny-story will be handled by calling (review-post req "a-funny-story"). And so on.