forked from marcoskirsch/nodemcu-httpserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserver.lua
More file actions
89 lines (79 loc) · 3.18 KB
/
Copy pathhttpserver.lua
File metadata and controls
89 lines (79 loc) · 3.18 KB
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
-- httpserver
-- Author: Marcos Skirsch
connectionTable = {}
-- Starts web server in the specified port.
return function (port)
local s = net.createServer(net.TCP, 10) -- 10 seconds client timeout
s:listen(
port,
function (connection)
local function onGet(connection, uri)
collectgarbage()
if #(uri.file) > 32 then
-- nodemcu-firmware cannot handle long filenames.
uri.args = {code = 400, errorString = "Bad Request"}
dofile("httpserver-error.lc")(connection, uri.args)
connection:close()
else
local fileExists = file.open(uri.file, "r")
file.close()
if not fileExists then
uri.args = {code = 404, errorString = "Not Found"}
dofile("httpserver-error.lc")(connection, uri.args)
connection:close()
elseif uri.isScript then
dofile(uri.file)(connection, uri.args)
connection:close()
else
uri.args = {file = uri.file, ext = uri.ext}
connectionTable[connection] = {bytesSent = 0, args = uri.args}
-- print("create: ", connection) -- for debugging
if dofile("httpserver-static.lc")(connection, uri.args, 1) == 0 then
connectionTable[connection] = nil
connection:close()
end
end
end
end
local function onReceive(connection, payload)
collectgarbage()
-- print(payload) -- for debugging
-- parse payload and decide what to serve.
local req = dofile("httpserver-request.lc")(payload)
print("Requested URI: " .. req.request)
if req.methodIsValid and req.method == "GET" then
onGet(connection, req.uri)
else
local args = {}
if req.methodIsValid then
args = {code = 501, errorString = "Not Implemented"}
else
args = {code = 400, errorString = "Bad Request"}
end
dofile("httpserver-error.lc")(connection, args)
connection:close()
end
end
local function onSent(connection, payload)
collectgarbage()
local args = connectionTable[connection].args
-- print("sent: ", connection) -- for debugging
if dofile("httpserver-static.lc")(connection, args, 0) == 0 then
connectionTable[connection] = nil
connection:close()
end
end
local function onDisconnection(connection, payload)
connectionTable[connection] = nil
end
connection:on("receive", onReceive)
connection:on("sent", onSent)
connection:on("disconnection", onDisconnection)
end
)
-- false and nil evaluate as false
local ip = wifi.sta.getip()
if not ip then ip = wifi.ap.getip() end
print("nodemcu-httpserver running at http://" .. ip .. ":" .. port)
return s
end