httpserver.lua 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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. local httpMethods = {GET=true, HEAD=true, POST=true, PUT=true, DELETE=true, TRACE=true, OPTIONS=true, CONNECT=true, PATCH=true}
  9. if httpMethods[method] then return method else return nil end
  10. end
  11. local function parseRequest(request)
  12. local e = request:find("\r\n", 1, true)
  13. if not e then return nil end
  14. local line = request:sub(1, e - 1)
  15. local r = {}
  16. _, i, r.method, r.uri = line:find("^([A-Z]+) (.-) HTTP/[1-9]+.[1-9]+$")
  17. return r
  18. end
  19. local function uriToFilename(uri)
  20. return "http/" .. string.sub(uri, 2, -1)
  21. end
  22. local function onError(connection, errorCode, errorString)
  23. print(errorCode .. ": " .. errorString)
  24. connection:send("HTTP/1.0 " .. errorCode .. " " .. errorString .. "\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n")
  25. connection:send("<html><head><title>" .. errorCode .. " - " .. errorString .. "</title></head><body><h1>" .. errorCode .. " - " .. errorString .. "</h1></body></html>\r\n")
  26. end
  27. local function parseArgs(args)
  28. local r = {}; i=1
  29. if args == nil or args == "" then return r end
  30. for arg in string.gmatch(args, "([^&]+)") do
  31. local name, value = string.match(arg, "(.*)=(.*)")
  32. if name ~= nil then r[name] = value end
  33. i = i + 1
  34. end
  35. return r
  36. end
  37. local function parseUri(uri)
  38. local r = {}
  39. if uri == nil then return r end
  40. if uri == "/" then uri = "/index.html" end
  41. questionMarkPos, b, c, d, e, f = uri:find("?")
  42. if questionMarkPos == nil then
  43. r.file = uri:sub(1, questionMarkPos)
  44. r.args = {}
  45. else
  46. r.file = uri:sub(1, questionMarkPos - 1)
  47. r.args = parseArgs(uri:sub(questionMarkPos+1, #uri))
  48. end
  49. _, r.ext = r.file:match("(.+)%.(.+)")
  50. r.isScript = r.ext == "lua" or r.ext == "lc"
  51. r.file = uriToFilename(r.file)
  52. return r
  53. end
  54. local function getMimeType(ext)
  55. -- A few MIME types. No need to go crazy in this list. If you need something that is missing, let's add it.
  56. local mt = {}
  57. mt.css = "text/css"
  58. mt.gif = "image/gif"
  59. mt.html = "text/html"
  60. mt.ico = "image/x-icon"
  61. mt.jpeg = "image/jpeg"
  62. mt.jpg = "image/jpeg"
  63. mt.js = "application/javascript"
  64. mt.png = "image/png"
  65. if mt[ext] then return mt[ext] end
  66. -- default to text.
  67. return "text/plain"
  68. end
  69. local function onGet(connection, uri)
  70. local uri = parseUri(uri)
  71. local fileExists = file.open(uri.file, "r")
  72. if not fileExists then
  73. onError(connection, 404, "Not Found")
  74. else
  75. if uri.isScript then
  76. file.close()
  77. collectgarbage()
  78. dofile(uri.file)(connection, uri.args)
  79. else
  80. -- Use HTTP/1.0 to ensure client closes connection.
  81. connection:send("HTTP/1.0 200 OK\r\nContent-Type: " .. getMimeType(uri.ext) .. "\r\Cache-Control: private, no-store\r\n\r\n")
  82. -- Send file in little 128-byte chunks
  83. while true do
  84. local chunk = file.read(128)
  85. if chunk == nil then break end
  86. connection:send(chunk)
  87. end
  88. file.close()
  89. end
  90. end
  91. collectgarbage()
  92. end
  93. local function onReceive(connection, payload)
  94. --print(payload) -- for debugging
  95. -- parse payload and decide what to serve.
  96. local req = parseRequest(payload)
  97. print("Requested URI: " .. req.uri)
  98. req.method = validateMethod(req.method)
  99. if req.method == nil then onError(connection, 400, "Bad Request")
  100. elseif req.method == "GET" then onGet(connection, req.uri)
  101. else onError(connection, 501, "Not Implemented") end
  102. connection:close()
  103. end
  104. local function handleRequest(connection)
  105. connection:on("receive", onReceive)
  106. end
  107. -- Starts web server in the specified port.
  108. function httpserver.start(port, clientTimeoutInSeconds)
  109. s = net.createServer(net.TCP, clientTimeoutInSeconds)
  110. s:listen(port, handleRequest)
  111. print("nodemcu-httpserver running at " .. wifi.sta.getip() .. ":" .. port)
  112. return s
  113. end