httpserver-static.lua 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. <<<<<<< HEAD
  8. 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"}
  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. =======
  16. 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"}
  17. if mt[ext] then return mt[ext] else return "text/plain" end
  18. >>>>>>> 2357415466bb24cba8ee33109146f6a6a2df0282
  19. end
  20. local function sendHeader(connection, code, codeString, mimeType)
  21. connection:send("HTTP/1.0 " .. code .. " " .. codeString .. "\r\nServer: nodemcu-httpserver\r\nContent-Type: " .. mimeType["contentType"] .. "\r\n")
  22. if mimeType["gzip"] then
  23. connection:send("Content-Encoding: gzip\r\n")
  24. end
  25. connection:send("Connection: close\r\n\r\n")
  26. end
  27. return function (connection, args)
  28. --print(args.ext)
  29. sendHeader(connection, 200, "OK", getMimeType(args.ext))
  30. --print("Begin sending:", args.file)
  31. -- Send file in little chunks
  32. local continue = true
  33. local bytesSent = 0
  34. while continue do
  35. -- NodeMCU file API lets you open 1 file at a time.
  36. -- So we need to open, seek, close each time in order
  37. -- to support multiple simultaneous clients.
  38. file.open(args.file)
  39. file.seek("set", bytesSent)
  40. local chunk = file.read(512)
  41. file.close()
  42. if chunk == nil then
  43. continue = false
  44. else
  45. coroutine.yield()
  46. connection:send(chunk)
  47. bytesSent = bytesSent + #chunk
  48. --print("Sent" .. args.file, bytesSent)
  49. end
  50. end
  51. --print("Finished sending:", args.file)
  52. end