nodemcu-firmware/lua_modules/http/http-example.lua

38 lines
1.3 KiB
Lua
Raw Permalink Normal View History

2015-01-19 18:12:06 +01:00
------------------------------------------------------------------------------
-- HTTP server Hello world example
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <dronnikov@gmail.com>
------------------------------------------------------------------------------
require("httpserver").createServer(80, function(req, res)
2015-01-19 18:12:06 +01:00
-- analyse method and url
2015-01-19 21:32:16 +01:00
print("+R", req.method, req.url, node.heap())
2015-01-19 18:12:06 +01:00
-- setup handler of headers, if any
req.onheader = function(self, name, value) -- luacheck: ignore
print("+H", name, value)
2015-01-19 18:12:06 +01:00
-- E.g. look for "content-type" header,
-- setup body parser to particular format
-- if name == "content-type" then
-- if value == "application/json" then
-- req.ondata = function(self, chunk) ... end
-- elseif value == "application/x-www-form-urlencoded" then
-- req.ondata = function(self, chunk) ... end
-- end
-- end
end
-- setup handler of body, if any
req.ondata = function(self, chunk) -- luacheck: ignore
2015-01-19 18:12:06 +01:00
print("+B", chunk and #chunk, node.heap())
if not chunk then
-- reply
res:send(nil, 200)
res:send_header("Connection", "close")
res:send("Hello, world!\n")
2015-01-19 18:12:06 +01:00
res:finish()
end
end
-- or just do something not waiting till body (if any) comes
--res:finish("Hello, world!")
2015-01-19 21:32:16 +01:00
--res:finish("Salut, monde!")
2015-01-19 18:12:06 +01:00
end)