example-3.scm 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. (use-modules (web server))
  2. (use-modules (web request)
  3. (web response)
  4. (web uri))
  5. (use-modules (sxml simple))
  6. ;; =========================
  7. ;; REQUEST/RESPONSE HANDLING
  8. ;; =========================
  9. (define* (respond #:optional body #:key
  10. (status 200)
  11. (title "This is my title!")
  12. (doctype "<!DOCTYPE html>\n")
  13. (content-type-params '((charset . "utf-8")))
  14. (content-type 'text/html)
  15. (extra-headers '())
  16. ;; if a body is provided use its templatized form
  17. (sxml (and body (templatize title body))))
  18. ;; as before, answer in two parts, headers and body
  19. (values (build-response #:code status
  20. ;; headers are an alist
  21. #:headers `((content-type . (,content-type ,@content-type-params))
  22. ,@extra-headers))
  23. ;; instead of returning the body as a string, respond gives
  24. ;; a procedure, which will be called by the web server to
  25. ;; write out the response to the client.
  26. ;; So you have 2 options: return string or return procedure which takes a port.
  27. (λ (port)
  28. (if sxml
  29. (begin
  30. (if doctype (display doctype port))
  31. (sxml->xml sxml port))))))
  32. (define (request-path-components request)
  33. ;; just for showing what the functions do
  34. (display (simple-format #f "(request-uri request): ~a\n"
  35. (request-uri request)))
  36. (display (simple-format #f "(uri-path ...): ~a\n"
  37. (uri-path (request-uri request))))
  38. (display (simple-format #f "(split-and-decode-uri-path ...): ~a\n"
  39. (split-and-decode-uri-path (uri-path (request-uri request)))))
  40. ;; actual logic
  41. ;; split the string that represents the uri and decode any url-endoced things
  42. (split-and-decode-uri-path
  43. ;; get the uri path as a string from the request struct
  44. (uri-path
  45. ;; get the request struct
  46. (request-uri request))))
  47. (define (debug-page request body)
  48. ;; use respond helper
  49. (respond
  50. ;; will be templatized
  51. `((h1 "hello world!")
  52. (table
  53. (tr (th "header") (th "value"))
  54. ;; splice in all request headers
  55. ,@(map (lambda (pair)
  56. `(tr (td (tt ,(with-output-to-string
  57. (lambda () (display (car pair))))))
  58. (td (tt ,(with-output-to-string
  59. (lambda ()
  60. (write (cdr pair))))))))
  61. (request-headers request))))))
  62. ;; =========
  63. ;; TEMPLATES
  64. ;; =========
  65. (define (templatize title body)
  66. `(html (head (title ,title))
  67. (body ,@body)))
  68. ;; ======
  69. ;; SERVER
  70. ;; ======
  71. (run-server debug-page)