【问题标题】:Deno 1.9 native webserver API and methods?Deno 1.9 原生网络服务器 API 和方法?
【发布时间】:2021-07-10 13:41:45
【问题描述】:

我试图在Deno 1.9 release notes 上找到更多关于本机HTTP/2 服务器的API 的信息。我的目标是在 HTTP/2 服务器上使用服务器发送的事件 (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));
    }
  })();
}

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

【问题讨论】:

    标签: http2 server-sent-events deno


    【解决方案1】:

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

    当我写下这个答案时,Deno 的原生 HTTP 服务器仍然被标记为“不稳定”。此后 API 已稳定,因此现在可以在此处查看文档:https://doc.deno.land/deno/stable/~/Deno.RequestEvent

    总结是给你一个Request object,并负责构建/响应Response object。 Response 构造函数上的 MDN 页面在显示响应请求时的选项方面应该非常有用。

    这个例子展示了一个带有正文、状态码和一个额外的标头的响应:

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

    关于 SSE:Deno 目前没有内置服务器发送事件功能,因此就 Deno API 而言,SSE 流看起来像任何其他流式响应。

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

    如果您想要更多地 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);
      }
    }
    

    然后您将能够通过调用您的生成器函数来响应请求(在通过路径或 Accepts 标头确认它是 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) 或 https://crux.land/84V4F (Deno 1.17),可以像这样调用:deno run --unstable --allow-net=0.0.0.0 https://crux.land/84V4F 并包含一个测试页面,显示收到的 SSE 事件.

    【讨论】:

      猜你喜欢
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 2012-06-05
      • 2015-03-31
      • 2015-05-24
      相关资源
      最近更新 更多