http-example.lua 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. ------------------------------------------------------------------------------
  2. -- HTTP server Hello world example
  3. --
  4. -- LICENCE: http://opensource.org/licenses/MIT
  5. -- Vladimir Dronnikov <dronnikov@gmail.com>
  6. ------------------------------------------------------------------------------
  7. require("httpserver").createServer(80, function(req, res)
  8. -- analyse method and url
  9. print("+R", req.method, req.url, node.heap())
  10. -- setup handler of headers, if any
  11. req.onheader = function(self, name, value) -- luacheck: ignore
  12. print("+H", name, value)
  13. -- E.g. look for "content-type" header,
  14. -- setup body parser to particular format
  15. -- if name == "content-type" then
  16. -- if value == "application/json" then
  17. -- req.ondata = function(self, chunk) ... end
  18. -- elseif value == "application/x-www-form-urlencoded" then
  19. -- req.ondata = function(self, chunk) ... end
  20. -- end
  21. -- end
  22. end
  23. -- setup handler of body, if any
  24. req.ondata = function(self, chunk) -- luacheck: ignore
  25. print("+B", chunk and #chunk, node.heap())
  26. if not chunk then
  27. -- reply
  28. res:send(nil, 200)
  29. res:send_header("Connection", "close")
  30. res:send("Hello, world!\n")
  31. res:finish()
  32. end
  33. end
  34. -- or just do something not waiting till body (if any) comes
  35. --res:finish("Hello, world!")
  36. --res:finish("Salut, monde!")
  37. end)