MCPcopy Create free account
hub / github.com/denoland/std / fetchExactPath

Function fetchExactPath

http/file_server_test.ts:55–109  ·  view source on GitHub ↗
(
  hostname: string,
  port: number,
  path: string,
)

Source from the content-addressed store, hash-verified

53
54/* HTTP GET request allowing arbitrary paths */
55async function fetchExactPath(
56 hostname: string,
57 port: number,
58 path: string,
59): Promise<Response> {
60 const encoder = new TextEncoder();
61 const decoder = new TextDecoder();
62 const conn = await Deno.connect({ hostname, port });
63 await conn.write(encoder.encode("GET " + path + " HTTP/1.1\r\n\r\n"));
64 let currentResult = "";
65 let contentLength = -1;
66 let startOfBody = -1;
67 for await (const chunk of conn.readable) {
68 currentResult += decoder.decode(chunk);
69 if (contentLength === -1) {
70 const match = /^content-length: (.*)$/m.exec(currentResult);
71 if (match && match[1]) {
72 contentLength = Number(match[1]);
73 }
74 }
75 if (startOfBody === -1) {
76 const ind = currentResult.indexOf("\r\n\r\n");
77 if (ind !== -1) {
78 startOfBody = ind + 4;
79 }
80 }
81 if (startOfBody !== -1 && contentLength !== -1) {
82 const byteLen = encoder.encode(currentResult).length;
83 if (byteLen >= contentLength + startOfBody) {
84 break;
85 }
86 }
87 }
88 const status = /^HTTP\/1.1 (...)/.exec(currentResult);
89 let statusCode = 0;
90 if (status && status[1]) {
91 statusCode = Number(status[1]);
92 }
93
94 const body = currentResult.slice(startOfBody);
95 const headersStr = currentResult.slice(0, startOfBody);
96 const headersReg = /^(.*): (.*)$/mg;
97 const headersObj: { [i: string]: string } = {};
98 let match = headersReg.exec(headersStr);
99 while (match !== null) {
100 if (match[1] && match[2]) {
101 headersObj[match[1]] = match[2];
102 }
103 match = headersReg.exec(headersStr);
104 }
105 return new Response(body, {
106 status: statusCode,
107 headers: new Headers(headersObj),
108 });
109}
110
111Deno.test("serveDir() sets last-modified header", async () => {
112 const req = new Request("http://localhost/test_file.txt");

Callers 1

Calls 2

writeMethod · 0.65
sliceMethod · 0.45

Tested by

no test coverage detected