httpserver.lua 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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. if uri == "/" then return "http/index.html" end
  29. return "http/" .. string.sub(uri, 2, -1)
  30. end
  31. local function onError(connection, errorCode, errorString)
  32. print(errorCode .. ": " .. errorString)
  33. connection:send("HTTP/1.0 " .. errorCode .. " " .. errorString .. "\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n")
  34. connection:send("<html><head><title>" .. errorCode .. " - " .. errorString .. "</title></head><body><h1>" .. errorCode .. " - " .. errorString .. "</h1></body></html>\r\n")
  35. connection:close()
  36. end
  37. local function parseUri(uri)
  38. if uri == "/" then uri = "/index.html" end
  39. print ("uri is " .. uri)
  40. questionMarkPos, b, c, d, e, f = uri:find("?")
  41. r = {}
  42. if questionMarkPos == nil then
  43. r.file = uri:sub(1, questionMarkPos)
  44. else
  45. r.file = uri:sub(1, questionMarkPos - 1)
  46. r.args = uri:sub(questionMarkPos+1, #uri)
  47. end
  48. _, r.ext = r.file:match("(.+)%.(.+)")
  49. return r
  50. end
  51. local function getMimeType(ext)
  52. -- A few MIME types. No need to go crazy in this list. If you need something that is missing, let's add it.
  53. local mimeTypes = {}
  54. mimeTypes.css = "text/css"
  55. mimeTypes.gif = "image/gif"
  56. mimeTypes.htm = "text/html"
  57. mimeTypes.html = "text/html"
  58. mimeTypes.ico = "image/x-icon"
  59. mimeTypes.jpe = "image/jpeg"
  60. mimeTypes.jpeg = "image/jpeg"
  61. mimeTypes.jpg = "image/jpeg"
  62. mimeTypes.js = "application/javascript"
  63. mimeTypes.png = "image/png"
  64. mimeTypes.txt = "text/plain"
  65. if mimeTypes[ext] then return mimeTypes[ext] end
  66. -- default to text.
  67. return "text/plain"
  68. end
  69. local function onGet(connection, uri)
  70. print("onGet: requested uri is: " .. uri)
  71. local fileExists = file.open(uriToFilename(uri), "r")
  72. if not fileExists then
  73. onError(connection, 404, "Not Found")
  74. else
  75. uri = parseUri(uri)
  76. -- Use HTTP/1.0 to ensure client closes connection.
  77. connection:send("HTTP/1.0 200 OK\r\nContent-Type: " .. getMimeType(uri.ext) .. "\r\Cache-Control: private, no-store\r\n\r\n")
  78. -- Send file in little 128-byte chunks
  79. while true do
  80. local chunk = file.read(128)
  81. if chunk == nil then break end
  82. connection:send(chunk)
  83. end
  84. connection:close()
  85. file.close()
  86. end
  87. end
  88. local function onReceive(connection, payload)
  89. print ("onReceive: We have a customer!")
  90. --print(payload) -- for debugging
  91. -- parse payload and decide what to serve.
  92. parsedRequest = parseRequest(payload)
  93. parsedRequest.method = validateMethod(parsedRequest.method)
  94. if parsedRequest.method == nil then onError(connection, 400, "Bad Request")
  95. elseif parsedRequest.method == "GET" then onGet(connection, parsedRequest.uri)
  96. else onNotImplemented(connection, 501, "Not Implemented") end
  97. end
  98. local function onSent(connection)
  99. print ("onSent: Thank you, come again.")
  100. end
  101. local function handleRequest(connection)
  102. connection:on("receive", onReceive)
  103. connection:on("sent", onSent)
  104. end
  105. -- Starts web server in the specified port.
  106. function httpserver.start(port, clientTimeoutInSeconds)
  107. server = net.createServer(net.TCP, clientTimeoutInSeconds)
  108. server:listen(port, handleRequest)
  109. print("nodemcu-httpserver running at " .. wifi.sta.getip() .. ":" .. port)
  110. return server
  111. end
  112. -- Stops the server.
  113. function httpserver.stop(server)
  114. server:close()
  115. end