-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.jl
executable file
·127 lines (98 loc) · 2.17 KB
/
server.jl
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
using HttpServer, Lazy
include("./pages/UserBiometrics.jl")
function stack(handlers)
reversed = reverse(handlers)
function compose(index, func)
if index < length(reversed)
prev = func
next_i = index + 1
child = reversed[next_i]
function next(args)
if isa(args, Tuple)
req, res = args
func(req, res)
else
return args
end
end
composed = next ∘ child
return compose(next_i, composed)
else
return func
end
end
return function(req, res)
index = 1
app = compose(index, reversed[index])
return app(req, res)
end
end
function hello(req, res)
@show "hello"
return req, res
end
function hi(req, res)
@show "hi"
req[:resource] == "/" ? "hi" : (req, res)
end
splitpath(p::AbstractString) = split(p, "/", keep=false)
splitpath(p) = p
function todict(req::Request, res::Response)
req′ = Dict()
req′[:method] = req.method
req′[:headers] = req.headers
req′[:resource] = req.resource
# req.data != "" && (req′[:data] = req.data)
return req′, res
end
function get_path(req, res)
req[:path] = splitpath(req[:resource])
return req, res
end
function route_test(req, res)
@show "route_test"
path = req[:path]
if (length(path) == 1 && path[1] == "test")
@show "route_test_return"
return "you routed to /test"
else
return req, res
end
end
function sub_route_test(req, res)
@show "sub_route_test"
path = req[:path]
if (length(path) > 0 && path[1] == "test")
return "you routed to /test/something"
else
return req, res
end
end
function unfold(iter)
result = []
for x in iter
if isa(x, Array)
push!(result, unfold(x))
else
push!(result, x)
end
end
result
end
function main(args...)
handlers = unfold(args)
app = stack(handlers)
handler = HttpHandler(app)
handler.events["error"] = (client, error) -> println(error)
handler.events["listen"] = (port) -> println("Listening on $port...")
return Server(handler)
end
test_routes = [route_test, sub_route_test]
server = main(
todict,
get_path,
stack(test_routes),
hello,
hi
)
run(server, 8000)