resource.sjs (2374B)
1 /* Generic responder that composes a response from 2 * the query string of a request. 3 * 4 * It reserves some special prop names: 5 * - body: get's used as the response body 6 * - statusCode: override the 200 OK response code 7 * (response text is set automatically) 8 * 9 * Any property names it doesn't know about get converted into 10 * HTTP headers. 11 * 12 * For example: 13 * http://test/resource.sjs?Content-Type=text/html&body=<h1>hello</h1>&Hello=hi 14 * 15 * Outputs: 16 * HTTP/1.1 200 OK 17 * Content-Type: text/html 18 * Hello: hi 19 * <h1>hello</h1> 20 */ 21 //global handleRequest 22 "use strict"; 23 24 const HTTPStatus = new Map([ 25 [100, "Continue"], 26 [101, "Switching Protocol"], 27 [200, "OK"], 28 [201, "Created"], 29 [202, "Accepted"], 30 [203, "Non-Authoritative Information"], 31 [204, "No Content"], 32 [205, "Reset Content"], 33 [206, "Partial Content"], 34 [300, "Multiple Choice"], 35 [301, "Moved Permanently"], 36 [302, "Found"], 37 [303, "See Other"], 38 [304, "Not Modified"], 39 [305, "Use Proxy"], 40 [306, "unused"], 41 [307, "Temporary Redirect"], 42 [308, "Permanent Redirect"], 43 [400, "Bad Request"], 44 [401, "Unauthorized"], 45 [402, "Payment Required"], 46 [403, "Forbidden"], 47 [404, "Not Found"], 48 [405, "Method Not Allowed"], 49 [406, "Not Acceptable"], 50 [407, "Proxy Authentication Required"], 51 [408, "Request Timeout"], 52 [409, "Conflict"], 53 [410, "Gone"], 54 [411, "Length Required"], 55 [412, "Precondition Failed"], 56 [413, "Request Entity Too Large"], 57 [414, "Request-URI Too Long"], 58 [415, "Unsupported Media Type"], 59 [416, "Requested Range Not Satisfiable"], 60 [417, "Expectation Failed"], 61 [500, "Internal Server Error"], 62 [501, "Not Implemented"], 63 [502, "Bad Gateway"], 64 [503, "Service Unavailable"], 65 [504, "Gateway Timeout"], 66 [505, "HTTP Version Not Supported"], 67 ]); 68 69 function handleRequest(request, response) { 70 const queryMap = new URLSearchParams(request.queryString); 71 if (queryMap.has("statusCode")) { 72 let statusCode = parseInt(queryMap.get("statusCode")); 73 let statusText = HTTPStatus.get(statusCode); 74 queryMap.delete("statusCode"); 75 response.setStatusLine("1.1", statusCode, statusText); 76 } 77 if (queryMap.has("body")) { 78 let body = queryMap.get("body") || ""; 79 queryMap.delete("body"); 80 response.write(decodeURIComponent(body)); 81 } 82 for (let [key, value] of queryMap.entries()) { 83 response.setHeader(key, value); 84 } 85 }