httpserver.lua 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. -- httpserver
  2. -- Author: Marcos Kirsch
  3. -- This is a very simple HTTP server designed to work on nodemcu (http://nodemcu.com)
  4. -- It can handle GET and POST.
  5. require "printTable"
  6. httpserver = {}
  7. -- Starts web server in the specified port.
  8. --function httpserver.start(port, clientTimeoutInSeconds, debug)
  9. -- -- Server constants
  10. -- server = net.createServer(net.TCP, clientTimeoutInSeconds) server:listen(port, private.handleRequest)
  11. --end
  12. httpserver.private = {} -- not part of the public API
  13. function httpserver.private.onReceive(connection, payload)
  14. print(payload) -- for debugging
  15. -- parse payload and decide what to serve.
  16. parsedRequest = private.parseRequest(payload)
  17. httpserver.private.printTable(parsedRequest, 3)
  18. --generates HTML web site
  19. httpHeader200 = "HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nCache-Control: private, no-store\r\n\r\n"
  20. html = "<h1>Hola mundo</h1>"
  21. connection:send(httpHeader200 .. html)
  22. end
  23. function httpserver.private.handleRequest(connection)
  24. connection:on("receive", onReceive)
  25. connection:on("sent",function(connection) connection:close() end)
  26. end
  27. -- given an HTTP request, returns the method (i.e. GET)
  28. function httpserver.private.getRequestMethod(request)
  29. -- HTTP Request Methods.
  30. -- HTTP servers are required to implement at least the GET and HEAD methods
  31. -- http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods
  32. httpMethods = {"GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "OPTIONS", "CONNECT", "PATCH"}
  33. method = nil
  34. for i=1,#httpMethods do
  35. found = string.find(request, httpMethods[i])
  36. if found == 1 then
  37. break
  38. end
  39. end
  40. return (httpMethods[found])
  41. end
  42. -- given an HTTP request, returns a table with all the information.
  43. function httpserver.private.parseRequest(request)
  44. parsedRequest = {}
  45. -- First get the method
  46. parsedRequest["method"] = httpserver.private.getRequestMethod(request)
  47. if parsedRequest["method"] == nil then
  48. return nil
  49. end
  50. -- Now get each value out of the header, skip the first line
  51. lineNumber = 0
  52. for line in request:gmatch("[^\r\n]+") do
  53. if lineNumber ~=0 then
  54. -- tag / value are of the style "Host: 10.0.7.15". Break them up.
  55. found, valueIndex = string.find(line, ": ")
  56. if found == nil then
  57. break
  58. end
  59. tag = string.sub(line, 1, found - 1)
  60. value = string.sub(line, found + 2, #line)
  61. parsedRequest[tag] = value
  62. end
  63. lineNumber = lineNumber + 1
  64. end
  65. return parsedRequest
  66. end