httpserver-static.lua 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. -- httpserver-static.lua
  2. -- Part of nodemcu-httpserver, handles sending static files to client.
  3. -- Author: Marcos Kirsch
  4. return function (connection, req, args)
  5. --print("Begin sending:", args.file)
  6. --print("node.heap(): ", node.heap())
  7. if args.isGzipped and req.isCheckModifiedRequest() then
  8. -- todo: really check if file updated
  9. dofile("httpserver-header.lc")(connection, 304, args.ext, args.isGzipped)
  10. else
  11. dofile("httpserver-header.lc")(connection, 200, args.ext, args.isGzipped)
  12. -- Send file in little chunks
  13. local continue = true
  14. local size = file.list()[args.file]
  15. local bytesSent = 0
  16. -- Chunks larger than 1024 don't work.
  17. -- https://github.com/nodemcu/nodemcu-firmware/issues/1075
  18. local chunkSize = 1024
  19. while continue do
  20. collectgarbage()
  21. -- NodeMCU file API lets you open 1 file at a time.
  22. -- So we need to open, seek, close each time in order
  23. -- to support multiple simultaneous clients.
  24. file.open(args.file)
  25. file.seek("set", bytesSent)
  26. local chunk = file.read(chunkSize)
  27. file.close()
  28. connection:send(chunk)
  29. bytesSent = bytesSent + #chunk
  30. chunk = nil
  31. --print("Sent: " .. bytesSent .. " of " .. size)
  32. if bytesSent == size then continue = false end
  33. end
  34. --print("Finished sending: ", args.file)
  35. end
  36. end