httpserver.lua 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. end
  35. local function parseUri(uri)
  36. if uri == "/" then uri = "/index.html" end
  37. questionMarkPos, b, c, d, e, f = uri:find("?")
  38. r = {}
  39. if questionMarkPos == nil then
  40. r.file = uri:sub(1, questionMarkPos)
  41. else
  42. r.file = uri:sub(1, questionMarkPos - 1)
  43. r.args = uri:sub(questionMarkPos+1, #uri)
  44. end
  45. _, r.ext = r.file:match("(.+)%.(.+)")
  46. r.isScript = r.ext == "lua"
  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. if uri.isScript then
  74. file.close()
  75. dofile(uriToFilename(uri.file))(connection, uri.args)
  76. else
  77. -- Use HTTP/1.0 to ensure client closes connection.
  78. connection:send("HTTP/1.0 200 OK\r\nContent-Type: " .. getMimeType(uri.ext) .. "\r\Cache-Control: private, no-store\r\n\r\n")
  79. -- Send file in little 128-byte chunks
  80. while true do
  81. local chunk = file.read(128)
  82. if chunk == nil then break end
  83. connection:send(chunk)
  84. end
  85. file.close()
  86. end
  87. end
  88. collectgarbage()
  89. end
  90. local function onReceive(connection, payload)
  91. --print(payload) -- for debugging
  92. -- parse payload and decide what to serve.
  93. local parsedRequest = parseRequest(payload)
  94. print("Requested URI: " .. parsedRequest.uri)
  95. parsedRequest.method = validateMethod(parsedRequest.method)
  96. if parsedRequest.method == nil then onError(connection, 400, "Bad Request")
  97. elseif parsedRequest.method == "GET" then onGet(connection, parsedRequest.uri)
  98. else onNotImplemented(connection, 501, "Not Implemented") end
  99. connection:close()
  100. end
  101. local function onSent(connection)
  102. print ("onSent: Thank you, come again.")
  103. end
  104. local function handleRequest(connection)
  105. connection:on("receive", onReceive)
  106. connection:on("sent", onSent)
  107. end
  108. -- Starts web server in the specified port.
  109. function httpserver.start(port, clientTimeoutInSeconds)
  110. server = net.createServer(net.TCP, clientTimeoutInSeconds)
  111. server:listen(port, handleRequest)
  112. print("nodemcu-httpserver running at " .. wifi.sta.getip() .. ":" .. port)
  113. return server
  114. end
  115. -- Stops the server.
  116. function httpserver.stop(server)
  117. server:close()
  118. end