httpserver.lua 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. if not fileExists then
  23. uri.args['code'] = 404
  24. fileServeFunction = dofile("httpserver-error.lc")
  25. elseif uri.isScript then
  26. collectgarbage()
  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 then
  44. if req.method == "GET" then onGet(connection, req.uri)
  45. else dofile("httpserver-static.lc")(conection, {code=501}) end
  46. else
  47. dofile("httpserver-static.lc")(conection, {code=400})
  48. end
  49. end
  50. local function onSent(connection, payload)
  51. local connectionThreadStatus = coroutine.status(connectionThread)
  52. -- print (connectionThread, "status is", connectionThreadStatus)
  53. if connectionThreadStatus == "suspended" then
  54. -- Not finished sending file, resume.
  55. -- print("Resume thread", connectionThread)
  56. coroutine.resume(connectionThread)
  57. elseif connectionThreadStatus == "dead" then
  58. -- We're done sending file.
  59. -- print("Done thread", connectionThread)
  60. connection:close()
  61. connectionThread = nil
  62. end
  63. end
  64. connection:on("receive", onReceive)
  65. connection:on("sent", onSent)
  66. end
  67. )
  68. if wifi.sta.getip() then print("nodemcu-httpserver running at http://" .. wifi.sta.getip() .. ":" .. port)
  69. else print("nodemcu-httpserver running at http://" .. wifi.ap.getip() .. ":" .. port)
  70. end
  71. return s
  72. end