httpserver-static.lua 1.1 KB

123456789101112131415161718192021222324252627
  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", josn="application/json", 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. sendHeader(connection, 200, "OK", getMimeType(args.ext))
  14. file.open(args.file)
  15. -- Send file in little chunks
  16. while true do
  17. local chunk = file.read(1024)
  18. if chunk == nil then break end
  19. coroutine.yield()
  20. connection:send(chunk)
  21. end
  22. print("Finished sending:", args.file)
  23. file.close()
  24. end