-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttplistener.tiny
350 lines (298 loc) · 13 KB
/
httplistener.tiny
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
################################################
#
# Simple HttpListener-based web serve in Tiny
#
################################################
import 'htmlutils'
import 'utils'
import 'IO'
options = Utils.GetOpts('httplistener', args, {
port: 4096
verbose: false
browser: false
formOnly: false
})
# If there's an error processing options, it will return null
# and the script should exit.
if (options == null) {
return null
}
stopwatch = utils.NewStopWatch()
prefix = format("http://localhost:{0}/", options.Port)
println("Http Server listening at " + prefix)
# Create the http listener if it doesn't already exist
# in the global scope.
if (__global !:> 'listener') {
__global.listener = [<system.net.httplistener>].new()
__global.listener.Prefixes.Add(prefix)
}
__global.listener.Start()
queryDefaults = {
Number1: 0
Number2: 0
ShowTables: 'off'
}
# Utility function to parse a query string into a hashtable
fn parseQuery str {
# Initialize the hashtable
query = {};
# split the query elements and extract the names and value
matchlist (str /~ '&')
| r/([^=]*)=([^=]*)'/:qe -> query[qe[1]] = qe[2]
# return the populated hashtable
query + queryDefaults
}
# If the 'browser' option was specified then open a web browser on ourselves
if (options.browser) {
url = prefix + 'sum?number1=0&number2=0&ShowTables=off'
alert('Opening browser on {0}', url)
start(url)
}
if (options.formonly) {
alert("Showing form only.")
}
else {
alert('Showing form and tables.')
}
try {
requestCount = 0
# The main application loop.
while (true) {
# Synchronously wait for a request
context = __global.listener.GetContext()
# start timing the response
stopwatch.reset()
stopwatch.start()
# Process the request object and print a message
requestCount += 1
request = context.Request
println("Request #{0} URL: {1}", requestCount, request.RawUrl)
if ((qs = request.RawUrl /~ '\?')?.Count > 1) {
_ = qs + queryDefaults
query = qs[1] |> parseQuery
println "QueryString:"
OutHost(query)
}
else {
println '<No query elements, using defaults>'
query = queryDefaults
}
# If the URL contains 'stop' then exit the listener loop
request.RawUrl ~ 'stop' then {
alert "\nReceived stop command."
break
}
# Prepare the response
response = context.Response
if (options.Verbose) {
println('Generating the response string.');
}
# Style for alternating rows of color in tables; not used currently
# tr:nth-child(even) {background-color: #f2f2f2;}
# The HTML string to return as the response
responseString =
html {
head : {
h1 "The Tiny Webserver"
# Set up styles for the document
style '
table {
border: 1px solid black;
}
th {
padding: 10px;
text-align: center;
background-color: #e0e0e0;
}
tr {
Background-color: #f2f2f2;
}
td {
padding: 10px;
text-align: left;
}
input[type=button], input[type=submit], input[type=reset] {
background-color: #909090;
border: none;
width: 100%;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
'
}
body : {
h2 "Hi there from Tiny!"
h3 ("Today is " + getDate().DayOfWeek)
form {
action: '/'
method: 'get'
body: {
table {border: '0px'} {
tr {
td 'Enter a number: '
td (input {type: 'number' name: 'number1' value: query?.number1})
}
tr {
td 'Enter a second number:'
td (input {type: 'number' name: 'number2' value: query?.number2})
}
if (query) {
match request.RawUrl
| r/sum/ ->
tr {
td (format('The sum of {0} plus {1} is:', query.number1, query.number2))
td (b (asnumber(query.number1) + (asnumber(query.number2))))
}
| r/times/ ->
tr {
td (format('The product of {0} times {1} is:', query.number1, query.number2))
td (b (asnumber(query.number1) * (asnumber(query.number2))))
}
| r/minus/ ->
tr {
td (format('The difference of {0} minus {1} is:', query.number1, query.number2))
td (b (asnumber(query.number1) - (asnumber(query.number2))))
}
| r/divide/ ->
tr {
td (format('The result of {0} divided by {1} is:', query.number1, query.number2))
td (b (asnumber(query.number1) / (asnumber(query.number2))))
}
| ->
tr {
td ''
td ''
}
}
else {
tr {
td ''
td ''
}
}
tr {
td (input {type: "submit" value:"Sum Numbers" size: 20 formAction: '/sum'})
td (input {type: "submit" value:"Multiply Numbers" size:20 formAction: '/times'})
}
tr {
td (input {type: "submit" value:"Subtract Numbers" size: 20 formAction: '/minus'})
td (input {type: "submit" value:"Divide Numbers" size: 20 formAction: '/divide'})
}
tr {
td (input {type:"submit" value:'Push Me To Stop The Server' formAction: '/stop'})
td (
input {
type: 'checkbox'
name: 'showTables'
label: 'Select to display tables'
checked: if (query.ShowTables == 'on') {
"checked"
}
else {
''
}
}
)
}
}
}
}
stopwatch.stop()
elapsed = stopwatch.elapsed.TotalMilliSeconds
stopwatch.start()
println("Form generation took {0} ms.", elapsed)
if ( query.ShowTables == 'on' ) {
# Need the div tag so all output is captured.
div {
h2 'The 10 Processes with the Largest Working Set'
table {width: "80%"} {
# add the headers
tr {
th 'ProcessName';
th 'WorkingSet'
th 'CPU'
th 'ID'
}
# now generate the table data
utils.getprocesses()
.sortdescending{it.ws}
.take(10)
.map{
p = it
tr {
td (p?.processname);
td (p?.ws)
td (p?.cpu)
td (p?.id)
}
}
}
stopwatch.stop()
println("Process table generation took {0} ms.\n\n---------\n",
stopwatch.elapsed.TotalMilliSeconds - elapsed)
elapsed = stopwatch.elapsed.TotalMilliSeconds
stopwatch.start()
h2 'The Largest files in this directory'
table {width: "80%"} {
# headers for the second table
tr {
th 'Name';
th 'Length'
th 'Extension'
th 'Mode'
}
# now generate the table data
shell('ls -file')
.sortdescending{it.length}
.take(10)
.map{
file = it;
tr {
td (file.Name)
td (file.Length)
td (file.Extension)
td (file.Mode)
}
}
}
stopwatch.stop()
println("File size table generation took {0} ms.\n\n---------\n",
stopwatch.Elapsed.TotalMilliSeconds - elapsed)
stopwatch.start()
}
}
}
}
if (options.Verbose) {
println("-------------------------")
println(responseString)
println("-------------------------")
}
# Turn the response string into a byte array
if (options.Verbose) {
println('Encoding response.')
}
buffer = Utils.GetBytes(responseString);
# Write the response
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Close()
if (options.Verbose) {
println('Wrote response.')
}
stopwatch.Stop()
println("Request Complete. Request took {0} ms.\n",
stopwatch.elapsed.TotalMilliSeconds)
}
}
catch {
error(it)
}
finally {
# Close the listener on exit
println("Server exiting; processed {0} requests. Goodbye.", requestCount)
__global.Listener.Stop()
}