forked from jponge/golo-devoxx13-demos
-
Notifications
You must be signed in to change notification settings - Fork 1
/
demo-10.golo
91 lines (77 loc) · 2.15 KB
/
demo-10.golo
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
module templates.webapp
import java.lang
import java.io
import java.net.InetSocketAddress
import com.sun.net.httpserver
import com.sun.net.httpserver.HttpServer
# A beautiful Golo template
local function index_template = -> """
<%@params posts %>
<!DOCTYPE html>
<html>
<head>
<title>Golo Chat</title>
</head>
<body>
<form action="/" method="post">
<input type="text" name="msg">
<input type="submit" value="Send">
</form>
<div>
<h3>Last posts</h3>
<% foreach post in posts { %>
<div>
<%= post %>
</div>
<% } %>
</div>
</body>
</html>
"""
function main = |args| {
# Model
let posts = java.util.concurrent.ConcurrentLinkedDeque()
# Server
let server = HttpServer.create(InetSocketAddress("localhost", 8081), 0)
# Get a template function
let index_tpl = TemplateEngine(): compile(index_template())
# "Dependency injection"
let index = ^index: bindTo(posts): bindTo(index_tpl)
# Server start
server: createContext("/", handler(index))
server: start()
println(">>> http://localhost:8081/")
}
# HTTP requests on /
local function index = |posts, template, exchange| {
if exchange: getRequestMethod() == "POST" {
extract_post(exchange, posts)
redirect(exchange, "/")
} else {
respond(exchange, template(posts))
}
}
local function respond = |exchange, body| {
exchange: getResponseHeaders(): set("Content-Type", "text/html")
exchange: sendResponseHeaders(200, body: length())
exchange: getResponseBody(): write(body: getBytes())
exchange: close()
}
local function redirect = |exchange, to| {
exchange: getResponseHeaders(): set("Location", to)
exchange: sendResponseHeaders(303, 0)
exchange: close()
}
local function handler = |func| -> func: to(HttpHandler.class)
# This is leaky and works with just 1 POST parameter...
local function extract_post = |exchange, posts| {
let reader = BufferedReader(InputStreamReader(exchange: getRequestBody()))
var line = reader: readLine()
while line isnt null {
if line: startsWith("msg=") {
posts: add(java.net.URLDecoder.decode(line: substring(4), "UTF-8"))
}
line = reader: readLine()
}
reader: close()
}