httpserver-static.lua 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. local gzip = false
  6. -- A few MIME types. Keep list short. If you need something that is missing, let's add it.
  7. local mt = {css = "text/css", gif = "image/gif", html = "text/html", ico = "image/x-icon", jpeg = "image/jpeg", jpg = "image/jpeg", js = "application/javascript", json = "application/json", png = "image/png"}
  8. -- add comressed flag if file ends with gz
  9. if ext:find("%.gz$") then
  10. ext = ext:sub(1, -4)
  11. gzip = true
  12. end
  13. if mt[ext] then contentType = mt[ext] else contentType = "text/plain" end
  14. return {contentType = contentType, gzip = gzip }
  15. end
  16. local function sendHeader(connection, code, codeString, mimeType)
  17. connection:send("HTTP/1.0 " .. code .. " " .. codeString .. "\r\nServer: nodemcu-httpserver\r\nContent-Type: " .. mimeType["contentType"] .. "\r\n")
  18. if mimeType["gzip"] then
  19. connection:send("Content-Encoding: gzip\r\n")
  20. end
  21. connection:send("Connection: close\r\n\r\n")
  22. end
  23. return function (connection, args)
  24. sendHeader(connection, 200, "OK", getMimeType(args.ext))
  25. --print("Begin sending:", args.file)
  26. -- Send file in little chunks
  27. local continue = true
  28. local bytesSent = 0
  29. while continue do
  30. -- NodeMCU file API lets you open 1 file at a time.
  31. -- So we need to open, seek, close each time in order
  32. -- to support multiple simultaneous clients.
  33. file.open(args.file)
  34. file.seek("set", bytesSent)
  35. local chunk = file.read(512)
  36. file.close()
  37. if chunk == nil then
  38. continue = false
  39. else
  40. coroutine.yield()
  41. connection:send(chunk)
  42. bytesSent = bytesSent + #chunk
  43. --print("Sent" .. args.file, bytesSent)
  44. end
  45. end
  46. --print("Finished sending:", args.file)
  47. end