@@ -787,4 +787,68 @@ Will expand out to:
787
787
788
788
The router component uses https://github.com/metosin/reitit[Reitit], a
789
789
popular data-driven routing library for Clojure. Other routing libreries
790
- can be used, but for this documentation we'll assume the default.
790
+ can be used, but for this documentation we'll use the default.
791
+
792
+ === Handlers
793
+
794
+ Let's take a closer look at function associated with the route.
795
+
796
+ .src/todo/routes.clj
797
+ [,clojure]
798
+ ----
799
+ (ns todo.routes)
800
+
801
+ (defn index [_options]
802
+ (fn [_request]
803
+ [:html {:lang "en"}
804
+ [:head [:title "Hello World Wide Web"]]
805
+ [:body [:h1 "Hello World Wide Web"]]]))
806
+ ----
807
+
808
+ This function returns another function, known as a
809
+ https://github.com/ring-clojure/ring[Ring] handler. Usually this
810
+ function will return a response map, but in this case we're returning a
811
+ https://github.com/weavejester/hiccup[Hiccup] vector.
812
+
813
+ Hiccup is a format for representing HTML as a Clojure data structure.
814
+ Elements are represented by a vector starting with a keyword, followed
815
+ by an optional attribute map and then the element body.
816
+
817
+ The `:site` feature of the web module adds middleware to turn Hiccup
818
+ vectors into HTML response maps. If the response is a vector, it wraps
819
+ the vector in response map. If the response is already a map, it checks
820
+ the `:body` of the response for a vector.
821
+
822
+ If we wanted a custom status code or headers, then the full response
823
+ map could be returned.
824
+
825
+ [,clojure]
826
+ ----
827
+ (defn index [_options]
828
+ (fn [_request]
829
+ {:status 200
830
+ :headers {}
831
+ :body [:html {:lang "en"}
832
+ [:head [:title "Hello World Wide Web"]]
833
+ [:body [:h1 "Hello World Wide Web"]]]))
834
+ ----
835
+
836
+ NOTE: The `:status` and `:headers` keys map optionally be omitted.
837
+
838
+ Or we could return the string directly:
839
+
840
+ [,clojure]
841
+ ----
842
+ (defn index [_options]
843
+ (fn [_request]
844
+ {:status 200
845
+ :headers {"Content-Type" "text/html;charset=UTF-8"}
846
+ :body "<!DOCTYPE html>
847
+ <html lang=\"en\">
848
+ <head><title>Hello World Wide Web</title></head>
849
+ <body><h1>Hello World Wide Web</h1></body>
850
+ </html>
851
+ ----
852
+
853
+ All of these examples are equivalent, but returning a vector is the most
854
+ convenient and concise.
0 commit comments