server.rkt 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #lang racket
  2. ;; ==============
  3. ;; PREDEFINITIONS
  4. ;; ==============
  5. (define (Mb-to-B n) (* n 1024 1024))
  6. (define MAX-BYTES (Mb-to-B 128))
  7. (define nil '())
  8. (custodian-limit-memory (current-custodian) MAX-BYTES)
  9. ;; =======================
  10. ;; PROVIDING AND REQUIRING
  11. ;; =======================
  12. (provide/contract
  13. (start (-> request? response?)))
  14. (require web-server/templates
  15. web-server/servlet-env
  16. web-server/servlet
  17. web-server/dispatch
  18. racket/date
  19. "apps/unknown-page.rkt"
  20. "apps/blog.rkt")
  21. ;; ======
  22. ;; MACROS
  23. ;; ======
  24. (define-syntax-rule (add-route route method proc)
  25. (dispatch-rules! blog-container
  26. [route #:method method proc]))
  27. ;; ====================
  28. ;; ROUTES MANAGING CODE
  29. ;; ====================
  30. (define (start request)
  31. ;; for now only calling the dispatch
  32. ;; we could put some action here, which shall happen before each dispatching
  33. (blog-dispatch request))
  34. (define-container blog-container (blog-dispatch a-url)) ;; what can we do with a container?
  35. (add-route ("") "get" blog-app)
  36. (add-route ("page" (integer-arg)) "get" blog-app)
  37. (add-route ("post" (integer-arg)) "get" post-app)
  38. (add-route ("tag" (string-arg)) "get" tag-app)
  39. (add-route ("tag" (string-arg) "page" (integer-arg)) "get" tag-app)
  40. ;; =================
  41. ;; RUNNING A SERVLET
  42. ;; =================
  43. (serve/servlet
  44. start
  45. #:servlet-path "/index" ; default URL
  46. #:extra-files-paths (list (build-path (current-directory) "static")) ; directory for static files
  47. #:port 8000 ; the port on which the servlet is running
  48. #:servlet-regexp #rx""
  49. #:launch-browser? false ; should racket show the servlet running in a browser upon startup?
  50. ;; #:quit? false ; ???
  51. #:listen-ip false ; the server will listen on ALL available IP addresses, not only on one specified
  52. #:server-root-path (current-directory)
  53. #:file-not-found-responder respond-unknown-file)
  54. ;; from the Racket documentation:
  55. ;; When you use web-server/dispatch with serve/servlet, you almost always want to use the #:servlet-regexp argument with the value "" to capture all top-level requests. However, make sure you don’t include an else in your rules if you are also serving static files, or else the filesystem server will never see the requests.
  56. ;; https://docs.racket-lang.org/web-server/dispatch.html