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