You are looking at historical revision 15376 of this page. It may differ significantly from its current revision.
Description
uri-dispatch is a simple mechanism to dispatch uris to procedures. This is useful for webprogramming where you might want to map uris of a certain kind to procedures that implement the logic for those uris.
Author
Requirements
Requires the uri-common and environments extensions.
Documentation
[procedure] (dispatch-uri URI)The main interface to dispatch-uri. This procedure invokes the dispatch-mechanism with the supplied uri. The dispatch-algorithm is implemented as follows:
- The path is empty. It checks if default-dispatch-target is non-false. If it is, then it is invoked. If it is not dispatch-error is invoked.
- The path has exactly one element. It assumes that this is this element is the name of a thunk that was defined outside a module. If the such a thunk exists it is invoked. If no such a thunk exists it invokes dispatch-error.
- The path contains at least two elements.
- It checks if the second element is a procedure defined in a module named by the first element. So if it sees (foo bar) it tries to find the procedure foo inside the module bar. If the procedure exists it is invoked with the rest of the elements as arguments.
- If it does not exist, it interpretes the first element as the name of a procedure that was defined outside any module. If such a procedure exists, it is invoked passing the rest of the elements as arguments. If no such procedure exists dispatch-error is invoked with the full path as argument.
Examples
<pre>
(use spiffy intarweb uri-common uri-dispatch)
(define (my-dispatch-error . path)
(send-status 404 (sprintf "My Dispatch-error ~A" path)))
(module example
(echo webiota) (import scheme chicken srfi-1 extras) (require-library spiffy) (import (only spiffy send-status)) (define (webiota #!optional (start "0") (steps "10") #!rest rest) (send-status 200 (sprintf "webiota called: ~A" (iota (string->number steps) (string->number start))))) (define (echo . args) (send-status 200 (sprintf "echo: ~A" args))))
(define (outsidemodule . args) (send-status 200 "Outside module"))
(vhost-map `(("localhost" . ,(lambda (continue)
(parameterize ((handle-not-found (lambda (path) (dispatch-uri (request-uri (current-request))))) (dispatch-error (lambda path (send-status 404 (sprintf "Path not found: ~A" path))))) (continue))))))
(start-server)
</pre>
Now start the server and visit the following pages:
- http://localhost:8080/example/webiota/2/10/
- http://localhost:8080/example/webiota/2/20/
- http://localhost:8080/example/webiota/echo/this/please
- http://localhost:8080/outsidemodule
- http://localhost:8080/i/do/not/exist