httpserver.lua 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. -- httpserver
  2. -- Author: Marcos Kirsch
  3. module("httpserver", package.seeall)
  4. -- Functions below aren't part of the public API
  5. -- Clients don't need to worry about them.
  6. -- given an HTTP method, returns it or if invalid returns nil
  7. local function validateMethod(method)
  8. -- HTTP Request Methods.
  9. -- HTTP servers are required to implement at least the GET and HEAD methods
  10. -- http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods
  11. local httpMethods = {"GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "OPTIONS", "CONNECT", "PATCH"}
  12. for i=1,#httpMethods do
  13. if httpMethods[i] == method then
  14. return method
  15. end
  16. end
  17. return nil
  18. end
  19. function parseRequest(request)
  20. local e = request:find("\r\n", 1, true)
  21. if not e then return nil end
  22. local line = request:sub(1, e - 1)
  23. local r = {}
  24. _, i, r.method, r.uri = line:find("^([A-Z]+) (.-) HTTP/[1-9]+.[1-9]+$")
  25. return r
  26. end
  27. local function uriToFilename(uri)
  28. return "http/" .. string.sub(uri, 2, -1)
  29. end
  30. local function onError(connection, errorCode, errorString)
  31. print(errorCode .. ": " .. errorString)
  32. connection:send("HTTP/1.0 " .. errorCode .. " " .. errorString .. "\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n")
  33. connection:send("<html><head><title>" .. errorCode .. " - " .. errorString .. "</title></head><body><h1>" .. errorCode .. " - " .. errorString .. "</h1></body></html>\r\n")
  34. connection:close()
  35. end
  36. local function parseUri(uri)
  37. if uri == "/" then uri = "/index.html" end
  38. questionMarkPos, b, c, d, e, f = uri:find("?")
  39. r = {}
  40. if questionMarkPos == nil then
  41. r.file = uri:sub(1, questionMarkPos)
  42. else
  43. r.file = uri:sub(1, questionMarkPos - 1)
  44. r.args = uri:sub(questionMarkPos+1, #uri)
  45. end
  46. _, r.ext = r.file:match("(.+)%.(.+)")
  47. return r
  48. end
  49. local function getMimeType(ext)
  50. -- A few MIME types. No need to go crazy in this list. If you need something that is missing, let's add it.
  51. local mimeTypes = {}
  52. mimeTypes.css = "text/css"
  53. mimeTypes.gif = "image/gif"
  54. mimeTypes.htm = "text/html"
  55. mimeTypes.html = "text/html"
  56. mimeTypes.ico = "image/x-icon"
  57. mimeTypes.jpe = "image/jpeg"
  58. mimeTypes.jpeg = "image/jpeg"
  59. mimeTypes.jpg = "image/jpeg"
  60. mimeTypes.js = "application/javascript"
  61. mimeTypes.png = "image/png"
  62. mimeTypes.txt = "text/plain"
  63. if mimeTypes[ext] then return mimeTypes[ext] end
  64. -- default to text.
  65. return "text/plain"
  66. end
  67. local function onGet(connection, uri)
  68. uri = parseUri(uri)
  69. local fileExists = file.open(uriToFilename(uri.file), "r")
  70. if not fileExists then
  71. onError(connection, 404, "Not Found")
  72. else
  73. -- Use HTTP/1.0 to ensure client closes connection.
  74. connection:send("HTTP/1.0 200 OK\r\nContent-Type: " .. getMimeType(uri.ext) .. "\r\Cache-Control: private, no-store\r\n\r\n")
  75. -- Send file in little 128-byte chunks
  76. while true do
  77. local chunk = file.read(128)
  78. if chunk == nil then break end
  79. connection:send(chunk)
  80. end
  81. connection:close()
  82. file.close()
  83. end
  84. end
  85. local function onReceive(connection, payload)
  86. print ("onReceive: We have a customer!")
  87. --print(payload) -- for debugging
  88. -- parse payload and decide what to serve.
  89. parsedRequest = parseRequest(payload)
  90. parsedRequest.method = validateMethod(parsedRequest.method)
  91. if parsedRequest.method == nil then onError(connection, 400, "Bad Request")
  92. elseif parsedRequest.method == "GET" then onGet(connection, parsedRequest.uri)
  93. else onNotImplemented(connection, 501, "Not Implemented") end
  94. end
  95. local function onSent(connection)
  96. print ("onSent: Thank you, come again.")
  97. end
  98. local function handleRequest(connection)
  99. connection:on("receive", onReceive)
  100. connection:on("sent", onSent)
  101. end
  102. -- Starts web server in the specified port.
  103. function httpserver.start(port, clientTimeoutInSeconds)
  104. server = net.createServer(net.TCP, clientTimeoutInSeconds)
  105. server:listen(port, handleRequest)
  106. print("nodemcu-httpserver running at " .. wifi.sta.getip() .. ":" .. port)
  107. return server
  108. end
  109. -- Stops the server.
  110. function httpserver.stop(server)
  111. server:close()
  112. end