httpserver-static.lua 1.1 KB

12345678910111213141516171819202122232425262728
  1. -- httpserver-static.lua
  2. -- Part of nodemcu-httpserver, handles sending static files to client.
  3. -- Author: Marcos Kirsch
  4. local function getMimeType(ext)
  5. -- A few MIME types. Keep list short. If you need something that is missing, let's add it.
  6. local mt = {css = "text/css",gif = "image/gif",html = "text/html",ico = "image/x-icon",jpeg = "image/jpeg",jpg = "image/jpeg",js = "application/javascript",png = "image/png"}
  7. if mt[ext] then return mt[ext] else return "text/plain" end
  8. end
  9. local function sendHeader(connection, code, codeString, mimeType)
  10. connection:send("HTTP/1.0 " .. code .. " " .. codeString .. "\r\nServer: nodemcu-httpserver\r\nContent-Type: " .. mimeType .. "\r\nConnection: close\r\n\r\n")
  11. end
  12. return function (connection, args)
  13. print("Serving:", args.file)
  14. sendHeader(connection, 200, "OK", getMimeType(args.ext))
  15. file.open(args.file)
  16. -- Send file in little chunks
  17. while true do
  18. local chunk = file.read(512)
  19. if chunk == nil then break end
  20. coroutine.yield()
  21. connection:send(chunk)
  22. end
  23. print("Finished sending file.")
  24. file.close()
  25. end