page_keep_alive_chunked.lua 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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("Last-Modified: " .. now .. " GMT\r\n")
  9. if not canKeepAlive then
  10. mg.write("Connection: close\r\n")
  11. mg.write("\r\n")
  12. mg.write("<html><body>Keep alive not possible!</body></html>")
  13. return
  14. end
  15. if mg.request_info.http_version ~= "1.1" then
  16. -- wget will use HTTP/1.0 and Connection: keep-alive, so chunked transfer is not possible
  17. mg.write("Connection: close\r\n")
  18. mg.write("\r\n")
  19. mg.write("<html><body>Chunked transfer is only possible for HTTP/1.1 requests!</body></html>")
  20. mg.keep_alive(false)
  21. return
  22. end
  23. -- use chunked encoding (http://www.jmarshall.com/easy/http/#http1.1c2)
  24. mg.write("Cache-Control: max-age=0, must-revalidate\r\n")
  25. --mg.write("Cache-Control: no-cache\r\n")
  26. --mg.write("Cache-Control: no-store\r\n")
  27. mg.write("Connection: keep-alive\r\n")
  28. mg.write("Transfer-Encoding: chunked\r\n")
  29. mg.write("\r\n")
  30. -- function to send a chunk
  31. function send(str)
  32. local len = string.len(str)
  33. mg.write(string.format("%x\r\n", len))
  34. mg.write(str.."\r\n")
  35. end
  36. -- send the chunks
  37. send("<html>")
  38. send("<head><title>Civetweb Lua script chunked transfer test page</title></head>")
  39. send("<body><pre>")
  40. send("1234567890")
  41. send("</pre></body>")
  42. send("</html>")
  43. -- end
  44. send("")