Racket URL dispatch

喜欢而已 提交于 2019-12-03 13:19:41

问题


I'm trying to hook up URL dispatch with Racket (formerly PLT Scheme). I've taken a look at the tutorial and the server documentation. I can't figure out how to route requests to the same servlets.

Specific example:

#lang scheme

(require web-server/servlet)
(require web-server/dispatch)
(provide/contract (start (request? . -> . response/c)))

(define (start request)
  (blog-dispatch request))

(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)))

(define (list-posts req) `(list-posts))
(define (review-post req p) `(review-post ,p))
(define (review-archive req y m) `(review-archive ,y ,m))

(require web-server/servlet-env)
(serve/servlet start
               #:launch-browser? #t
               #:quit? #f
               #:listen-ip #f
               #:port 8080
               #:extra-files-paths (list (build-path "js")
                                         (build-path "css"))
               #:servlet-path "")

Assuming the above code, localhost:8080/ goes to a page that says "list-posts". Going to localhost:8080/posts/test goes to a Racket "file not found" page (I'd expect it to go to a page that says "review-post test").

It feels like I'm missing something small and obvious. Can anyone give me a hint?


回答1:


What you've written is not a whole program, so I cannot debug it.

Here is a program with annotations that does what you want, probably:

#lang scheme ; specify the right language
; include the correct libraries
(require web-server/servlet
         ; this one gets "serve/servlet"
         web-server/servlet-env)

(define (start request)
  (blog-dispatch request))

(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)))

(define (list-posts req) `(list-posts))
(define (review-post req p) `(review-post ,p))
(define (review-archive req y m) `(review-archive ,y ,m))

; starts a web server where...
(serve/servlet start ; answers requests
               #:servlet-path "" ; is the default URL
               #:port 8080 ; is the port
               #:servlet-regexp #rx"") ; is a regexp decide
                                       ; if 'start' should
                                       ; handle the request

Because the functions list-posts, review-post, and review-archive don't return sensible xexpr encodings of HTML, you'll have to view source to see them right.

Please feel free to email me directly or email the PLT Scheme mailing list. (Note: We are renaming PLT Scheme to "Racket" so you may see that when you post.)

Jay McCarthy



来源:https://stackoverflow.com/questions/2879092/racket-url-dispatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!