default.ss
#lang scheme/base
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SHP: Hypertext Processor
;;
;; a PHP like web framework for PLT Scheme
;;
;; Bonzai Lab, LLC.  All rights reserved.
;;
;; Licensed under LGPL.
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; default.ss - for handling default requests that have not be overwritten yet.
;; yc 7/6/2010 - first version - a lot still resides in shp.ss that should be factored out.
(require "base.ss"
         "depend.ss"
         "script.ss" 
         )

#|
a default script runs during error conditions, and when there are no scripts that are written 
to handle the error. 

;;|#

;; the default-handlers uses hash (key = status code)
(define default-handlers (make-immutable-hash-registry)) 

;; wrapper for overwriting/setting the default handelr.
(define (default-handler-set! status handler) 
  (define (path-helper status)
    (string-append "/" (number->string status)))
  (registry-set! default-handlers 
                 status 
                 (if (script? handler)
                     handler 
                     (make-script handler (make-*path (path-helper status)
                                                      (path-helper status)
                                                      (path-helper status)
                                                      (current-seconds))))))
;; access the default handler
(define (default-handler-ref status)
  (registry-ref default-handlers status (lambda () 
                                          (error 'unknown-status "~a" status))))
;; delete the default handler - this is provided for completeness.
(define (default-handler-del! status)
  (registry-del! default-handlers status)) 

;; auth required
(default-handler-set! 401 
  (lambda args 
    `(p "Please provide your credential to access the resource.")))

;; forbidden
(default-handler-set! 403 
  (lambda args 
    `(p "You do not have permission to access the resource.")))

;; not-found
(default-handler-set! 404 
  (lambda args 
    `(p "We did not find what you are looking for.")))

;; internal-server-error
(default-handler-set! 500 
  (lambda (e)
    `(div (h3 "Error occured: ")
          (p ,(exn-message e)))))


(provide/contract 
 (default-handler-set! (-> integer? procedure? any)) 
 (default-handler-ref (-> integer? procedure?))
 (default-handler-del! (-> integer? any))
 )