-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathclojure_en.txt
1286 lines (1181 loc) · 30.5 KB
/
clojure_en.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Clojure - LISP on JVM
=====================
:author Pavel Tišnovský
:email <ptisnovs 0x40 redhat 0x2e com>
:date 2017-05-03
:where FI MUNI A318
Agenda
------
▶ Clojure - (not) yet another language for JVM
▶ Basic Clojure features
▶ Forms
▶ Collections
▶ Functions
▶ Lazy evaluation and lazy sequences
▶ Four reference types (variable substitution)
▶ Parallel programming
▶ Watchers
▶ Validators
▶ Macros
▶ Classes and objects in Clojure
▶ Cooperation between Java and Clojure
▶ Web apps (Clojure Ring philosophy)
▶ Testing
▶ Code coverage reporting
Clojure - (yet another) language for JVM
----------------------------------------
Java Virtual Machine
Specification implemented by more VMs
HotSpot
Client
Server
Azul
J9
JamVM
CACAO VM
Graal
Jikes RVM
JVM
---
JVM is scalable
No (apparent) GIL
Multi-threaded garbage collectors
Synchronized and unsynchronized variants of collections
Future interface
etc. etc. etc.
Supports dynamically typed programming languages
Java platform
-------------
Compiler+JVM+standard packages+other tools
Mature
evolving since 1985 now > 14M developers (TIOBE)
Stable and robust + rich standard libraries
Usually backward compatible
"Java is a modern COBOL"
Java is not the only language prepared to run on JVM
-----------------------------------------------------
JavaScript
Rhino
Nashorn
Scala
Groovy
Jython
JRuby
Kotlin
...
...
...
Clojure!
Java vs.Clojure?
----------------
Java vs. Clojure? not exactly...
Clojure is not replacement of Java
does not try to reinvent the wheel
cooperates nicely with Java libs
"Java interop"
Clojure
-------
▶ Clojure = Java + Closure
▶ Rich Hickey
▶ Based on LISP (and on Scheme too)
◆ Theory of λ-calculus
Alonzo Church
Look at the Clojure logo :)
◆ WEB2.0^W cloud^W social networks^W^W AI was the IT buzzword in 1950s
◆ John McCarthy 1956-1958
◆ Implemented by S.R.Russell (REPL)
▶ Three main implementations
◆ for JVM
◆ for .NET
◆ transpiled into JavaScript
Basic Clojure features
----------------------
Deadlock-free multi-threaded programs
Immutable data types
List (linked), vector (RRB Tree), hash map, set
very important feature in massive parallel applications
Agents
Software Transactional Memory (STM)
Support for transactions
Clojure contains REPL
Read-Eval-Print-Loop
Code == Data
-> Homoiconicity
Well, Clojure is a LISP variant...
Basic Clojure features
----------------------
Four reference types instead of simple "variables"
variables are a poor choice for many operations
sync/async operations
atomic operations
regular variable can't be "watched"
regular variable can't be validated simply
Basic Clojure features
----------------------
Lambda expressions
Closures
Explicit tail recursion
Clojure is lazy
ie it is like many humans (incl. /me)
Performs required work only when forced/asked
Lazy sequences
range function is a good example
Some work (computation) does not have to be performed ASAP
Let's start it in a background thread!
Java <--> Clojure communication
-------------------------------
Clojure can create an instance of a Java class and access its attributes and methods
JSR-292 support
Programs are compiled into JVM bytecode
On the fly
The best of "scripted" and "compiled" worlds :-)
With support for dynamic typing
Not an easy task (before invokedynamic)
LISP roots
----------
; side effect
(println "Hello" "world")
; + is regular function
(+ 1 2 3 4)
; nested functions
(* (+ 1 2 3) (+ 3 4))
; empty list != nil !!!
'()
()
; vector
[1 2 3 4]
; Clojure supports fractions
(/ (+ 1 2) (+ 3 4))
→ 3/7
Namespaces
----------
namespace/name
ns macro
no real "global" variables
Forms
-----
Literals
Numbers
Strings
Boolean values
Symbols and keywords
Compound forms
Lists
Vectors
Maps
Sets
Special forms
-------------
Special forms
if
def
creates a "global" var with the given name
do
new
calls the respective constructor of the given Java class
. (dot)
used to call methods of Java objects
quote
'(1 2 3 4)
etc.
Functions
---------
Functions have similar properties as other values
It's possible to create new functions in runtime
Function could be passed to other function as a parameter
Function could be returned by other function as its return value
Function could be stored in list, vector, map etc.
Name could be bind to a function
but it's not needed in all cases
anonymous functions
used extensivelly not only in Clojure
Anonymous functions
-------------------
Function definition
(fn [x y] (* x y))
((fn [x y] (* x y)) 6 7)
Short form of anonymous function definition
#(* % %)
#(* %1 %2)
(#(* %1 %2) 6 7)
Functions with name
-------------------
Functions behave as other values
(def multiply (fn [x y] (* x y)))
(multiply 6 7)
defn = def + fn
(defn multiply [x y] (* x y))
Referentially transparent functions
-----------------------------------
Don't access any global symbol
Without side-off effects (I/O)
Don't have internal state
those functions are not bound to application state
results can be cached
(memoization)
Multiarity functions
--------------------
(defn multiply
([x]
(* x x))
([x y]
(* x y))
([x y z]
(* x y z)))
Recursion vs tail recursion
---------------------------
Factorial - a typical example
(defn fact
[n]
(if (<= n 1)
1
(* n (fact (- n 1)))))
(fact 100M)
(fact 10000M)
StackOverflowError :)
Very deep recursion might cause stack overflow
"recur" special form
(defn fact
([n]
(fact n 1))
([n acc]
(if (<= n 1)
acc
(recur (dec n) (* acc n)))))
It is not possible to use "recur" everywhere
so called "tail position"
Memoization
-----------
(defn fact
[n]
(apply *
(range 1M (inc n))))
(dotimes [i 10] (time (fact 10000)))
(defn fact2
[n]
(memoize
(fn [n]
(apply *
(range 1M (inc n))))))
(dotimes [i 10] (time (fact2 10000)))
Collections
-----------
List, Vector, Map, Set
Immutable items
Persistent collections
It is not neccessary to clone a collection in case of some operations
pop/peek for lists
...
Basic functions for collection processing
-----------------------------------------
(count)
(empty)
(cons)
(conj)
(pop) ; lists vs vectors
(peek) ; lists vs vectors
(nth)
(first)
(rest)
Time complexity
---------------
# Function List Vector
1 count O(1) O(1)
2 nth O(N) O(log₃₂N)
3 pop O(1) O(log₃₂N)
4 peek O(1) O(log₃₂N)
5 first O(1) O(1)
6 last O(N) O(N)
Lists
------
Lists
Internally constist of:
first item
rest (sublist)
count
Program itself is represented by a sequence of lists!
Examples
'(1 2 3 4)
'()
'(1 (2 (3 (4 5))))
Vectors
-------
Vectors
used extensivelly in Clojure
Based on RRB-Trees, Relaxed Radix Balanced Trees
usually takes less memory than lists
<=32 items -> simple array
<=1024 items -> tree with height=2
root=32 references to 32-item vectors
<= 32768 items -> tree with height=3
and so on...
Examples
[1 2 3 4]
[ [1 2 3] [4 5 6] [7 8 9]]
Maps
----
~ dictionaries, hashtables
Sortable maps
Examples
{:one 1, :two 2}
{:one 1 :two 2}
Sets
----
Implemented as hash sets
Can't contain duplicate items
Sortable sets
Examples
#{"this" "is" "a" "set"}
#{1 1 3}
IllegalArgumentException
Sequences
---------
Sequence = iterator in other languages
Three basic operations
first
returns the first item in the collection/sequence
rest
returns (possibly empty) sequence of the items after the first item
next
returns a sequence of items after the first item
nil instead of empty sequence
All collections are sequences
Lazy sequences
--------------
Lazy sequence - computation is done ALAP
lazy-seq macro
iterate function
returns a lazy sequence of x, (f x), (f (f x))...
range function
repeat function
map
returns a lazy sequence
take
returns a lazy sequence of the first n items in coll
take-while
returns a lazy sequence of successive items from coll according to the given condition
filter
Lazy sequences
--------------
(map inc [1 2 3 4])
(map inc (range 1 9))
;
(map * [1 2 3 4] [5 6 7 8])
;
(def lazy (range))
(def lazy2 (map inc lazy))
(nth lazy2 10)
(take 10 lazy2)
;
(defn end-of? [x] (<= x 42))
(take-while end-of? (range 1 100 3))
;
(filter (fn [x] (< x 10)) (range 0 1000))
Four reference types (variable substitution)
--------------------------------------------
Vars
Refs
Atoms
Agents
Vars
----
synchronous state change
~ static variables in selected namespace
it is safe to use them locally in current thread
Constructor
(def name value)
Change value
set!
let - local symbols/vars
Refs
----
support transactions
synchronous state change
coordinated - state is changed inside transaction only
Constructor
(def name (ref value))
Get value
(deref name)
@name
Change value
dosync
transaction (STM, ACID, nested transactions possible)
ref-set
sets a new value
can be used only inside transaction
(checked by Clojure)
alter
change value by applying some function to ref
can be used only inside transaction
(checked by Clojure)
Refs
----
(def account-1 (ref 100000))
(def account-2 (ref 20000))
;
(defn transfer-money
[from to amount]
(dosync
(alter from - amount)
(alter to + amount)))
Atoms
-----
synchronous state change
change of value is "atomic"
other threads can use new value immediatelly
BUT other threads could "see" intermediate values
-> difference from Refs
Constructor
(def name (atom value))
Get value
(deref name)
@name
Change value
reset!
sets new value
swap!
calls function on the old value
Other
compare-and-set!
similar to test-and-set atomic oop
Atoms
-----
(def x (atom 42))
(deref x)
@x
(reset! x 10)
@x
(swap! x + 1)
@x
Agents
------
asynchronous state change
agent run its operation in new thread
more elegant than future/promise
Constructor
(def name (agent value))
Get value
(deref name)
@name
don't perform the synchronization!!!
-> you could get the wrong (old) value
Change value
send
sends function to agent's thread
send-off
sends function to agent's thread
Wait for agent
await
await-for
incl. timeout
Agents
------
(def my-agent (agent 0))
(send my-agent + 6)
(send my-agent * 7)
@my-agent
;
(def agent1 ....
...send slow computation
(def agent2 ....
...send slow computation
(await agent1 agent2)
Parallel programming
--------------------
pmap/pcalls/pvalues
pmap
parallel map
it isn't always better to parallelize things!
pmap is not always faster than map
pcalls
(pcalls func1 func2 func3 ...)
returns lazy sequence containing return values of called functions
(pcalls (fn [] (compute 10)) (fn [] (compute 20)) (fn [] (compute -1)))
pvalues
returns a lazy sequence of the values of the exprs, which are evaluated in parallel
(def results (pvalues (compute 10) (compute 20) (compute 30)))
agents
future and promise
STM - Software Transactional Memory
Future and promise
------------------
future
starts computation in a new thread
synchronization occurs only when deref (@) is called
easier to use than Future interface in Java
Helper functions
future-done?
future-cancel
(def future_fact (fact 20))
@future_fact
Future and promise
------------------
promise
can be used to implement a dataflow model
usually used together with a "future" object
three functions
promise
creates "promise" objects
deliver value
usually called from a "future" thread
only the first value is really set
deref value
might wait for the "future" thread to finish
deref == @
!!! can possibly lead to deadlock !!!
Future+promise dataflow
-----------------------
(def x (promise))
(def y (promise))
(def z (promise))
;
(def task-1
(future
(deliver z (@x @y))))
;
(def task-2
(future
(deliver x (fact 10))))
;
(def task-3
(future
(deliver y (fact 100))))
; now all three calculations are running
; first one needs to wait for other two
Watchers
--------
Watcher
Function "registered" to some reference
Automatically called when reference changes its value
Watcher is called in the same thread
Any number of watchers can be set for one reference
Watcher can be registered using:
(add-watch reference key function)
And unregistered using:
(remove-watch reference key)
Watchers
--------
(defn on-change
[key identity old-val new-val]
(println (str "Old value: " old-val))
(println (str "New value: " new-val)))
;
(def x (ref 42))
;
(add-watch x "watch-1" on-change)
;
(dosync (alter x + 1))
;
(dosync (alter x + 1) (alter x - 1 ))
Validators
----------
Validator
Function "registered" to some reference
Automatically called to check if reference value is correct
During write/set operations
Bypassed inside transaction!
Must return true/false
Any number of validators can be set for one reference
Validator can be registered using:
(set-validator! reference function)
Validators
----------
(def x (ref 42))
;
(set-validator! x (fn [val] (even? val)))
;
(dosync (ref-set x 10))
;
(dosync (alter x + 10))
;
(dosync (alter x + 1))
;
; check is not performed DURING transaction
(dosync (alter x + 1) (alter x + 1))
Macros
------
Macros are part of Clojure standard library
for
dotimes
while
lazy-seq
etc.
Reader macros
-------------
;
comment
\
Unicode literals (\u0040)...
^
used to add metadata to symbols, lists, ...
#
dispatch (various meaning)
'
(quote ....)
`
syntax quote
~
unquote
~@
unquote splicing
@
(deref ...)
Threading macros
----------------
->
(-> "/etc/passwd" slurp clojure.string/split-lines count)
->>
(->> (range) (take 20) (filter #(zero? (mod % 3))))
Cooperation between Java and Clojure
------------------------------------
Special function to access Java arrays
Constructors
new
(special form)
Methods
.
(special form)
Attributes
.
gets/reads a value
set!
sets/writes a value
Java interop
------------
(new String)
(new String "Hello world")
;
(. Integer valueOf "42")
(. Float MAX_VALUE)
;
(def my-string "Hello world")
(. my-string length)
;
(def rect (new java.awt.Rectange))
(set! (. rect width) 320)
(set! (. rect height) 200)
REPL
----
▶ Read Eval Print Loop
▶ Better to use it with Leiningen
Leiningen
---------
▶ "Maven for Clojure"
▶ Project handling
▶ Unit testing
▶ Supports plugins
▶ Run apps in devel mode
◆ Web apps atd.
▶ Better REPL
Project.clj
-----------
(defproject Test2 "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
[hiccup "1.0.4"]]
:main test.core)
More complicated project
------------------------
(defproject smearch "0.1.0-SNAPSHOT"
:description "The ultimate application"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/java.jdbc "0.3.3"]
[ring/ring-core "1.2.2"]
[ring/ring-jetty-adapter "1.2.2"]
[hiccup "1.0.4"]
[org.clojure/tools.cli "0.3.1"]]
:resource-paths ["resources/teiid-8.6.0.Final-jdbc.jar"]
:dev-dependencies [[lein-ring "0.8.10"]]
:plugins [[lein-ring "0.8.10"]]
:ring {:handler smearch.core/app}
:main smearch.core)
Leiningen and REPL
------------------
▶ Basic usage
◆ lein repl
▶ Leiningen REPL + Screen
◆ screen -S clojure
◆ lein repl
Web apps (Clojure Ring philosophy)
----------------------------------
Clojure Ring
Pure function to transform request->response
Basically Map -> Map
Well not that easy in real apps :)
Four components of web app:
Handler
Request
Response
Middleware
Request
A map with keys:
:server-port, :uri, :query-string, :headers, :request-method, :body (POST)
Response
A map with keys:
:status, :headers, :body
Middleware
Session processing
Params
Content type
HTTP code
etc.
Middleware
----------
(defn wrap-auth [handler]
(fn [request]
(if (authorized? request)
(handler request)
(-> (response "Access Denied")
(status 403)))))
Hiccup
------
(require '[hiccup.core :as hiccup])
(require '[hiccup.page :as page])
(require '[hiccup.form :as form])
;
(defn render-html-header
[]
[:head
[:title "Ultimate tool"]
[:meta {:name "Author" :content "Pavel Tisnovsky"}]
[:meta {:name "Generator" :content "Clojure"}]
[:meta {:http-equiv "Content-type" :content "text/html; charset=utf-8"}]
(page/include-css "bootstrap.min.css")
(page/include-js "bootstrap.min.js")
]
)
;
(defn render-page
[user-name]
(page/xhtml
(render-html-header)
[:body
[:div {:class "container"}
(form/form-to [:get "/" ]
(form/text-field {:autofocus "autofocus" :size "40"} "user-name" (str user-name))
(form/submit-button "Search"))
] ; </div class="container">
] ; </body>
))
Hiccup
------
(ns test.core)
;
(require '[hiccup.page :as page])
;
(defn factorial
([n]
(factorial n 1N)) ; dulezite -> donutime pouziti BigInteger
; (uz zadne IntegerOverflow :)
([n acc]
(if (= n 0) acc
(recur (dec n) (* acc n)))))
;
(defn render-factorials
[max-n]
(for [n (range 0 (inc max-n))]
[:tr [:td n] [:td (factorial n)]]))
;
(defn render-html-page
[]
(page/xhtml
[:head
[:title "Factorial generator"]
[:meta {:name "Author" :content "Pavel Tisnovsky"}]
[:meta {:name "Generator" :content "Clojure/hiccup"}]
[:meta {:http-equiv "Content-type" :content "text/html; charset=utf-8"}]
(page/include-css "style.css")
(page/include-js "scripts.js")
]
[:body
[:h1 "Factorial"]
[:table
[:tr [:th "n"] [:th "n!"]]
(render-factorials 100)
]]))
;
(defn -main
"Entry point"
[& args]
(spit "test.html" (render-html-page)))
Project file
------------
(defproject ringapp1 "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.6.0"]
[ring/ring-core "1.3.2"]
[ring/ring-jetty-adapter "1.3.2"]
[hiccup "1.0.4"]
[org.clojure/tools.cli "0.3.1"]]
:dev-dependencies [[lein-ring "0.8.10"]]
:plugins [[lein-ring "0.8.10"]]
:main ^:skip-aot ringapp1.core
:target-path "target/%s"
:ring {:handler ringapp1.core/app}
:profiles {:uberjar {:aot :all}})
Clojure Ring
------------
(ns servertest.core)
;
(require '[ring.adapter.jetty :as jetty])
(require '[ring.middleware.params :as http-params])
(require '[ring.util.response :as http-response])
;
(require '[hiccup.page :as page])
;
(defn render-page
[]
(page/xhtml
[:head
[:title "Hello world!"]
[:meta {:name "Author" :content "Pavel Tisnovsky"}]
[:meta {:name "Generator" :content "Clojure"}]
[:meta {:http-equiv "Content-type" :content "text/html; charset=utf-8"}]
]
[:body
[:h1 "Hello world!"]]))
;
(defn generate-response
[page-content]
(-> (http-response/response page-content)
(http-response/content-type "text/html")))
;
(defn handle-request
[request]
(generate-response (render-page)))
;
(defn handler
[request]
(handle-request request))
;
(def app
(-> handler
http-params/wrap-params))
;
(defn start-server
[port]
(println "Starting the server at the port: " port)
(jetty/run-jetty app {:port port}))
;
(defn -main
[& args]
(start-server 8080))
Requests processing
-------------------
(ns servertest2.core)
;
(require '[ring.adapter.jetty :as jetty])
(require '[ring.middleware.params :as http-params])
(require '[ring.util.response :as http-response])
;
(require '[hiccup.page :as page])
;
(defn render-page
[]
(page/xhtml
[:head
[:title "Hello world!"]
[:meta {:name "Author" :content "Pavel Tisnovsky"}]
[:meta {:name "Generator" :content "Clojure"}]
[:meta {:http-equiv "Content-type" :content "text/html; charset=utf-8"}]
]
[:body
[:h1 "Hello world!"]]))
;
(defn generate-response
[page-content]
(-> (http-response/response page-content)
(http-response/content-type "text/html")))
;
(defn print-request-info
[request]
(println "time: " (.toString (new java.util.Date)))
(println "addr: " (request :remote-addr))
(println "params: " (request :params))
(println "user-agent: " ((request :headers) "user-agent"))
(println ""))
;
(defn handle-request
[request]
(println "request URI: " (request :uri))
(print-request-info request)
(generate-response (render-page)))
;
(defn handler
[request]
(handle-request request))
;
(def app
(-> handler
http-params/wrap-params))
;
(defn start-server
[port]
(println "Starting the server at the port: " port)
(jetty/run-jetty app {:port port}))
;
(defn -main
[& args]
(start-server 8080))
Sessions
--------
(ns servertest3.core)
;