resource_script_demo.lua 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. -- This is a Lua script that handles sub-resources, e.g. resource_script_demo.lua/path/file.ext
  2. scriptUri = "resource_script_demo.lua"
  3. envVar = "resource_script_demo_storage"
  4. resourcedir = os.getenv(envVar)
  5. method = mg.request_info.request_method:upper()
  6. if resourcedir then
  7. attr = lfs.attributes(resourcedir)
  8. end
  9. if (not mg.request_info.uri:find(scriptUri)) or (not resourcedir) or (not attr) or (attr.mode~="directory") then
  10. mg.write("HTTP/1.0 500 OK\r\n")
  11. mg.write("Connection: close\r\n")
  12. mg.write("Content-Type: text/html; charset=utf-8\r\n")
  13. mg.write("\r\n")
  14. mg.write("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
  15. mg.write("<body>\r\nServer error.<br>\r\n")
  16. mg.write("The server admin must make sure this script is available as URI " .. scriptUri .. "<br>\r\n")
  17. mg.write("The server admin must set the environment variable " .. envVar .. " to a directory.<br>\r\n")
  18. mg.write("</body>\r\n</html>\r\n")
  19. return
  20. end
  21. subresource = mg.request_info.uri:match(scriptUri .. "(.*)")
  22. if not subresource then
  23. if method=="GET" then
  24. mg.write("HTTP/1.0 200 OK\r\n")
  25. mg.write("Connection: close\r\n")
  26. mg.write("Content-Type: text/html; charset=utf-8\r\n")
  27. mg.write("\r\n")
  28. mg.write("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
  29. mg.write("<body>No resource specified.</body></html>\r\n")
  30. else
  31. mg.write("HTTP/1.0 405 Method Not Allowed\r\n")
  32. mg.write("Connection: close\r\n")
  33. mg.write("Content-Type: text/html; charset=utf-8\r\n")
  34. mg.write("\r\n")
  35. mg.write("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
  36. mg.write("<body>Method not allowed.</body></html>\r\n")
  37. end
  38. return
  39. end
  40. if method=="GET" then
  41. file = resourcedir .. subresource
  42. if lfs.attributes(file) then
  43. mg.send_file(file)
  44. else
  45. mg.write("HTTP/1.0 404 Not Found\r\n")
  46. mg.write("Connection: close\r\n")
  47. mg.write("Content-Type: text/html; charset=utf-8\r\n")
  48. mg.write("\r\n")
  49. mg.write("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
  50. mg.write("<body>Resource not found.</body></html>\r\n")
  51. end
  52. return
  53. end
  54. -- Any other method
  55. mg.write("HTTP/1.0 405 Method Not Allowed\r\n")
  56. mg.write("Connection: close\r\n")
  57. mg.write("Content-Type: text/html; charset=utf-8\r\n")
  58. mg.write("\r\n")
  59. mg.write("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
  60. mg.write("<body>Method not allowed.</body></html>\r\n")