1function send_ok() 2 mg.write("HTTP/1.0 200 OK\r\n") 3 mg.write("Connection: close\r\n") 4 mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n") 5end 6 7 8function send_not_found() 9 mg.write("HTTP/1.0 404 Not Found\r\n") 10 mg.write("Connection: close\r\n") 11 mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n") 12end 13 14 15handler = "filehandler.lua" 16sub_uri = mg.request_info.uri:sub(#handler+2) 17filename = "D:\\civetweb\\civetweb" .. sub_uri 18attr = lfs.attributes(filename) 19 20--[[ 21if not attr then 22 send_not_found() 23 mg.write("\r\n") 24 mg.write("File " .. sub_uri .. " not available") 25 return 26end 27]] 28 29if mg.request_info.request_method == "GET" then 30 -- send_file will handle 404 internally 31 mg.send_file(filename) 32 return 33 34elseif mg.request_info.request_method == "HEAD" then 35 -- send_file can handle "GET" and "HEAD" 36 mg.send_file(filename) 37 return 38 39elseif mg.request_info.request_method == "PUT" then 40 local f = io.open(filename, "w") 41 if (not f) then 42 mg.write("HTTP/1.0 500 Internal Server Error\r\n") 43 mg.write("Connection: close\r\n") 44 mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n") 45 mg.write("\r\n") 46 return 47 end 48 49 mg.write("HTTP/1.0 201 Created\r\n") 50 mg.write("Connection: close\r\n") 51 mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n") 52 mg.write("\r\n") 53 repeat 54 local buf = mg.read(); 55 if (buf) then 56 f:write(buf) 57 end 58 until (not buf); 59 f:close() 60 61 mg.write("HTTP/1.0 201 Created\r\n") 62 mg.write("Connection: close\r\n") 63 mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n") 64 mg.write("\r\n") 65 return 66 67elseif mg.request_info.request_method == "DELETE" then 68 if not attr then 69 send_not_found() 70 mg.write("\r\n") 71 mg.write("File " .. sub_uri .. " not available") 72 return 73 end 74 os.remove(filename) 75 mg.write("HTTP/1.0 204 No Content\r\n") 76 mg.write("Connection: close\r\n") 77 mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n") 78 mg.write("\r\n") 79 return 80 81elseif mg.request_info.request_method == "OPTIONS" then 82 send_ok() 83 mg.write("Allow: GET, HEAD, PUT, DELETE, OPTIONS\r\n") 84 mg.write("\r\n") 85 return 86 87else 88 mg.write("HTTP/1.0 405 Method Not Allowed\r\n") 89 mg.write("Connection: close\r\n") 90 mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n") 91 mg.write("\r\n") 92 return 93end 94