dmac / spin

Write RESTful web apps in Racket.
MIT License
229 stars 18 forks source link

Define handlers passing a function that is used to build the full response #2

Closed felipecrv closed 11 years ago

felipecrv commented 11 years ago

It also adds a #:response-maker parameter to the run function. This code allow users to define customized request handlers.

EXAMPLE:

(define (json-response-maker status headers body)
  (response status
            (status->message status)
            (current-seconds)
            #"application/json; charset=utf-8"
            headers
            (let ([jsexpr-body (case status
                                 [(404) (string->jsexpr
                                         "{\"error\": 404, \"message\": \"Not Found\"}")]
                                 [else body])])
              (lambda (op) (write-json (force jsexpr-body) op)))))

Defining json-get:

(define (json-get path handler)
  (define-handler "GET" path handler json-response-maker))

Passing the json-response-maker to run:

(run

:port 8080

#:response-maker json-response-maker)

By doing this "404 Not Found" errors will be handled by json-response-maker.

felipecrv commented 11 years ago

I know this pull request adds a lot of complexity and changes a lot of code, but I'll leave it here.

dmac commented 11 years ago

This is a nice feature. I've added some docs and merged it in, thanks!