page_keep_alive_chunked.lua 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. -- Set keep_alive. The return value specifies if this is possible at all.
  2. canKeepAlive = mg.keep_alive(true)
  3. now = os.date("!%a, %d %b %Y %H:%M:%S")
  4. -- First send the http headers
  5. mg.write("HTTP/1.1 200 OK\r\n")
  6. mg.write("Content-Type: text/html\r\n")
  7. mg.write("Date: " .. now .. " GMT\r\n")
  8. mg.write("Cache-Control: no-cache\r\n")
  9. mg.write("Last-Modified: " .. now .. " GMT\r\n")
  10. if not canKeepAlive then
  11. mg.write("Connection: close\r\n")
  12. mg.write("\r\n")
  13. mg.write("<html><body>Keep alive not possible!</body></html>")
  14. return
  15. end
  16. if mg.request_info.http_version ~= "1.1" then
  17. -- wget will use HTTP/1.0 and Connection: keep-alive, so chunked transfer is not possible
  18. mg.write("Connection: close\r\n")
  19. mg.write("\r\n")
  20. mg.write("<html><body>Chunked transfer is only possible for HTTP/1.1 requests!</body></html>")
  21. mg.keep_alive(false)
  22. return
  23. end
  24. -- use chunked encoding (http://www.jmarshall.com/easy/http/#http1.1c2)
  25. mg.write("Cache-Control: max-age=0, must-revalidate\r\n")
  26. --mg.write("Cache-Control: no-cache\r\n")
  27. --mg.write("Cache-Control: no-store\r\n")
  28. mg.write("Connection: keep-alive\r\n")
  29. mg.write("Transfer-Encoding: chunked\r\n")
  30. mg.write("\r\n")
  31. -- function to send a chunk
  32. function send(str)
  33. local len = string.len(str)
  34. mg.write(string.format("%x\r\n", len))
  35. mg.write(str.."\r\n")
  36. end
  37. -- send the chunks
  38. send("<html>")
  39. send("<head><title>Civetweb Lua script chunked transfer test page</title></head>")
  40. send("<body>\n")
  41. fileCnt = 0
  42. if lfs then
  43. send("Files in " .. lfs.currentdir())
  44. send('\n<table border="1">\n')
  45. send('<tr><th>name</th><th>type</th><th>size</th></tr>\n')
  46. for f in lfs.dir(".") do
  47. local at = lfs.attributes(f);
  48. if at then
  49. send('<tr><td>' .. f .. '</td><td>' .. at.mode .. '</td><td>' .. at.size .. '</td></tr>\n')
  50. end
  51. fileCnt = fileCnt + 1
  52. end
  53. send("</table>\n")
  54. end
  55. send(fileCnt .. " entries (" .. now .. " GMT)\n")
  56. send("</body>")
  57. send("</html>")
  58. -- end
  59. send("")