http-example.lua 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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)
  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)
  25. print("+B", chunk and #chunk, node.heap())
  26. -- request ended?
  27. if not chunk then
  28. -- reply
  29. --res:finish("")
  30. res:send(nil, 200)
  31. res:send_header("Connection", "close")
  32. res:send("Hello, world!")
  33. res:finish()
  34. end
  35. end
  36. -- or just do something not waiting till body (if any) comes
  37. --res:finish("Hello, world!")
  38. --res:finish("Salut, monde!")
  39. end)