-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathserver.lua
78 lines (68 loc) · 2.04 KB
/
server.lua
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
-- https://github.com/szym/display
-- Copyright (c) 2015, Szymon Jakubczak (MIT License)
-- Forwards any data POSTed to /events to an event-stream at /events.
-- Serves files from /static otherwise.
local async = require('async')
local paths = require('paths')
local function getMime(ext)
if ext == '.css' then
return 'text/css'
elseif ext == '.js' then
return 'text/javascript'
else
return 'text/html' -- TODO: other mime types
end
end
local subscribers = {}
local function handler(req, res, client)
print(req.method, req.url.path)
if req.url.path == '/events' then
local headers = {
['Content-Type'] = 'text/event-stream',
['Cache-Control'] = 'no-cache',
['Connection'] = 'keep-alive',
['Transfer-Encoding'] = 'chunked'
}
if req.method == 'GET' then
res('', headers, 200)
table.insert(subscribers, client)
elseif req.method == 'POST' then
local body = req.body
for i=1,#subscribers do
local client = subscribers[i]
assert(type(body) == 'string')
-- send chunk
local headlen = 8
client.write(string.format('%x\r\n', #body + headlen))
client.write('data: ') -- 6
client.write(body)
client.write('\n\n') -- 2
client.write('\r\n')
end
res('', {})
else
res('Invalid method!', {}, 405)
end
else -- serve files from static
local path = req.url.path
if path == '/' or path == '' then
path = '/index.html'
end
local ext = string.match(path, "%.%l%l%l?")
local mime = getMime(ext)
local file = io.open(paths.dirname(paths.thisfile()) .. '/static' .. path, 'r')
if file ~= nil then
local content = file:read("*all")
file:close()
res(content, {['Content-Type']=mime})
else
res('Not found!', {}, 404)
end
end
end
function server(hostname, port)
async.http.listen('http://' .. hostname .. ':' .. port .. '/', handler)
print('server listening on http://' .. hostname .. ':' .. port)
async.go()
end
return server