cors.reply.lua 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. -- http://www.html5rocks.com/static/images/cors_server_flowchart.png
  2. if not mg.request_info.http_headers.Origin then
  3. mg.write("HTTP/1.0 200 OK\r\n")
  4. mg.write("Connection: close\r\n")
  5. mg.write("Content-Type: text/html; charset=utf-8\r\n")
  6. mg.write("\r\n")
  7. mg.write("This test page should not be used directly. Open cors.html instead.")
  8. return
  9. end
  10. if mg.request_info.request_method == "OPTIONS" then
  11. local acrm = mg.request_info.http_headers['Access-Control-Request-Method'];
  12. if (acrm) then
  13. local acrh = nil -- mg.request_info.http_headers['Access-Control-Request-Header'];
  14. if (acrm~='PUT') then
  15. -- invalid request
  16. mg.write("HTTP/1.0 403 Forbidden\r\n")
  17. mg.write("Connection: close\r\n")
  18. mg.write("\r\n")
  19. return
  20. else
  21. -- preflight request
  22. mg.write("HTTP/1.0 200 OK\r\n")
  23. mg.write("Access-Control-Allow-Methods: PUT\r\n")
  24. if (acrh) then
  25. mg.write("Access-Control-Allow-Headers: " .. acrh .. "\r\n")
  26. end
  27. mg.write("Access-Control-Allow-Origin: *\r\n")
  28. mg.write("Connection: close\r\n")
  29. mg.write("Content-Type: text/html; charset=utf-8\r\n")
  30. mg.write("\r\n")
  31. return
  32. end
  33. end
  34. end
  35. -- actual request
  36. if mg.request_info.request_method == "GET" then
  37. mg.write("HTTP/1.0 200 OK\r\n")
  38. mg.write("Access-Control-Allow-Origin: *\r\n")
  39. mg.write("Connection: close\r\n")
  40. mg.write("Content-Type: text/html; charset=utf-8\r\n")
  41. mg.write("\r\n")
  42. mg.write([[<!DOCTYPE html>
  43. <html>
  44. <head><title>CORS dynamic GET test reply - test OK</title></head>
  45. <body>This should never be shown</body>
  46. </html>
  47. ]])
  48. return
  49. end
  50. if mg.request_info.request_method == "PUT" then
  51. mg.write("HTTP/1.0 200 OK\r\n")
  52. mg.write("Access-Control-Allow-Origin: *\r\n")
  53. mg.write("Connection: close\r\n")
  54. mg.write("Content-Type: text/html; charset=utf-8\r\n")
  55. mg.write("\r\n")
  56. mg.write([[<!DOCTYPE html>
  57. <html>
  58. <head><title>CORS dynamic PUT test reply - test OK</title></head>
  59. <body>This should never be shown</body>
  60. </html>
  61. ]])
  62. return
  63. end
  64. mg.write("HTTP/1.0 403 Forbidden\r\n")
  65. mg.write("Connection: close\r\n")
  66. mg.write("\r\n")