httpserver.lua 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. -- httpserver
  2. -- Author: Marcos Kirsch
  3. -- Starts web server in the specified port.
  4. return function (port)
  5. local s = net.createServer(net.TCP, 10) -- 10 seconds client timeout
  6. s:listen(
  7. port,
  8. function (connection)
  9. -- This variable holds the thread used for sending data back to the user.
  10. -- We do it in a separate thread because we need to yield when sending lots
  11. -- of data in order to avoid overflowing the mcu's buffer.
  12. local connectionThread
  13. local function onGet(connection, uri)
  14. local fileServeFunction = nil
  15. if #(uri.file) > 32 then
  16. -- nodemcu-firmware cannot handle long filenames.
  17. uri.args['code'] = 400
  18. fileServeFunction = dofile("httpserver-error.lc")
  19. else
  20. local fileExists = file.open(uri.file, "r")
  21. file.close()
  22. collectgarbage()
  23. if not fileExists then
  24. uri.args['code'] = 404
  25. fileServeFunction = dofile("httpserver-error.lc")
  26. elseif uri.isScript then
  27. fileServeFunction = dofile(uri.file)
  28. else
  29. uri.args['file'] = uri.file
  30. uri.args['ext'] = uri.ext
  31. fileServeFunction = dofile("httpserver-static.lc")
  32. end
  33. end
  34. connectionThread = coroutine.create(fileServeFunction)
  35. --print("Thread created", connectionThread)
  36. coroutine.resume(connectionThread, connection, uri.args)
  37. end
  38. local function onReceive(connection, payload)
  39. -- print(payload) -- for debugging
  40. -- parse payload and decide what to serve.
  41. local req = dofile("httpserver-request.lc")(payload)
  42. print("Requested URI: " .. req.request)
  43. if req.methodIsValid and req.method == "GET" then
  44. onGet(connection, req.uri)
  45. else
  46. local args = {}
  47. if req.methodIsValid then args['code'] = 501 else args['code'] = 400 end
  48. dofile("httpserver-error.lc")(connection, args)
  49. end
  50. end
  51. local function onSent(connection, payload)
  52. local connectionThreadStatus = coroutine.status(connectionThread)
  53. -- print (connectionThread, "status is", connectionThreadStatus)
  54. if connectionThreadStatus == "suspended" then
  55. -- Not finished sending file, resume.
  56. -- print("Resume thread", connectionThread)
  57. coroutine.resume(connectionThread)
  58. elseif connectionThreadStatus == "dead" then
  59. -- We're done sending file.
  60. -- print("Done thread", connectionThread)
  61. connection:close()
  62. connectionThread = nil
  63. end
  64. end
  65. connection:on("receive", onReceive)
  66. connection:on("sent", onSent)
  67. end
  68. )
  69. local ip = nil
  70. if wifi.sta.getip() then ip = wifi.sta.getip() else ip = wifi.ap.getip() end
  71. print("nodemcu-httpserver running at http://" .. ip .. ":" .. port)
  72. return s
  73. end