cors.reply.lua 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. -- http://www.html5rocks.com/static/images/cors_server_flowchart.png
  2. if not mg.request_info.http_headers.Origin and 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. -- Note: This is a test example showing how a script could handle
  12. -- a preflight request directly. However, now the server is able
  13. -- to handle preflight requests, so scripts do no longer need to
  14. -- do this - except it has been disabled in the server by setting
  15. -- the access_control_allow_methods configuration parameter to
  16. -- an empty string.
  17. local acrm = mg.request_info.http_headers['Access-Control-Request-Method'];
  18. if (acrm) then
  19. local acrh = nil -- mg.request_info.http_headers['Access-Control-Request-Header'];
  20. if (acrm~='PUT') then
  21. -- invalid request
  22. mg.write("HTTP/1.0 403 Forbidden\r\n")
  23. mg.write("Connection: close\r\n")
  24. mg.write("\r\n")
  25. return
  26. else
  27. -- preflight request
  28. mg.write("HTTP/1.0 200 OK\r\n")
  29. mg.write("Access-Control-Allow-Methods: PUT\r\n")
  30. if (acrh) then
  31. mg.write("Access-Control-Allow-Headers: " .. acrh .. "\r\n")
  32. end
  33. mg.write("Access-Control-Allow-Origin: *\r\n")
  34. mg.write("Connection: close\r\n")
  35. mg.write("Content-Type: text/html; charset=utf-8\r\n")
  36. mg.write("\r\n")
  37. return
  38. end
  39. end
  40. end
  41. -- actual request
  42. if mg.request_info.request_method == "GET" then
  43. mg.write("HTTP/1.0 200 OK\r\n")
  44. mg.write("Access-Control-Allow-Origin: *\r\n")
  45. mg.write("Connection: close\r\n")
  46. mg.write("Content-Type: text/html; charset=utf-8\r\n")
  47. mg.write("\r\n")
  48. mg.write([[<!DOCTYPE html>
  49. <html>
  50. <head><title>CORS dynamic GET test reply - test OK</title></head>
  51. <body>This should never be shown</body>
  52. </html>
  53. ]])
  54. return
  55. end
  56. if mg.request_info.request_method == "PUT" then
  57. mg.write("HTTP/1.0 200 OK\r\n")
  58. mg.write("Access-Control-Allow-Origin: *\r\n")
  59. mg.write("Connection: close\r\n")
  60. mg.write("Content-Type: text/html; charset=utf-8\r\n")
  61. mg.write("\r\n")
  62. mg.write([[<!DOCTYPE html>
  63. <html>
  64. <head><title>CORS dynamic PUT test reply - test OK</title></head>
  65. <body>This should never be shown</body>
  66. </html>
  67. ]])
  68. return
  69. end
  70. -- other HTTP method
  71. mg.write("HTTP/1.0 403 Forbidden\r\n")
  72. mg.write("Connection: close\r\n")
  73. mg.write("\r\n")