Deno 1.9 原生网络服务器 API 和方法?

Deno 1.9 native webserver API and methods?

我正在尝试使用 HTTP/2 服务器在 Deno 1.9 release notes, about the API of the native HTTP/2 server. My aim is to use server sent events (SSE) 上查找更多信息。 发行说明中提供了以下代码:

const body = new TextEncoder().encode("Hello World");
for await (const conn of Deno.listen({ port: 4500 })) {
  (async () => {
    for await (const { respondWith } of Deno.serveHttp(conn)) {
      respondWith(new Response(body));
    }
  })();
}

我希望能够处理请求、发送 headers 等。因此,如果有人可以将我指向 API,那就太好了。

围绕 Deno.serveHttp 的 API 实际上非常基础,类似于 MDN 上记录的 ServiceWorker fetch-event API。

当我写这个答案时,Deno 的原生 HTTP 服务器仍然被标记为 'unstable'。 API 从那时起就稳定了,所以现在可以在这里查看文档:https://doc.deno.land/deno/stable/~/Deno.RequestEvent

总结就是给你一个Request object and are tasked with constructing/responding with a Response object。响应构造函数上的 MDN 页面在显示响应请求时的选项方面应该非常有用。

此示例显示了一个带有 body、状态代码和一个额外的 header:

的响应
    await evt.respondWith(new Response(someHtml, {
      status: 200,
      headers: new Headers({ "Content-Type": "text/html" }),
    }));

关于 SSE:目前 Deno 中没有内置 Server-Sent 事件功能,因此就 Deno API 而言,SSE 流看起来像任何其他流响应。

生成 SSE 事件的最简单方法是使用像 Oak 这样的 HTTP 库,它具有 native support for emitting events HTTP 响应。

如果你想做更多的 DIY,第一步是编写一个异步生成器函数来生成 SSE 有效负载流,例如这个实现每次生成 op_http_write 操作的累积指标第二个:

// Function generating the SSE-formatted data stream
async function* generateEvents() {
  while (true) {
    await new Promise((r) => setTimeout(r, 1000));
    const opMetrics = Deno.metrics().ops['op_http_write'];
    const message = `data: ${JSON.stringify(opMetrics)}\n\n`;
    yield new TextEncoder().encode(message);
  }
}

然后您将能够通过调用您的生成器函数来响应请求(在通过路径或接受 header 确认它是 SSE 之后):

import { readableStreamFromIterable } from "https://deno.land/std@0.95.0/io/streams.ts";

    const stream = readableStreamFromIterable(generateEvents());
    await respondWith(new Response(stream, {
      headers: new Headers({ "Content-Type": "text/event-stream" }),
    })).catch(err => { /* the client probably went away */ });

我已经将示例程序上传到 https://crux.land/61HZ4a (Deno 1.9) or https://crux.land/84V4F (Deno 1.17),可以像这样调用它:deno run --unstable --allow-net=0.0.0.0 https://crux.land/84V4F 并包含一个测试页面,显示接收到的 SSE 事件。