Way too iterate over Deno.serve connections?
Hi, as a lot of the old http api's are now deprecated, I would like to know if there is a nice way to achieve the following:
Create a
Deno.serve
instance, iterate over each request, my goal is to put this in an async generator that yields upgraded websockets.
This is doable with the Deno.listen
api, but now that the Deno.serveHttp
is deprecated, I'm not sure how to proceed.
Thanks.3 Replies
Hello! 🦕
To iterate over connections using
Deno.serve
, you can use the new stable API that simplifies the process of setting up a web server. Here's an example from the documentation that demonstrates how to create a server and handle requests:
In this example, serve
is a function that takes a handler function as an argument. The handler function is called for each incoming request, and you can respond to each request with a Response
object.
If you want to upgrade connections to WebSockets within this setup, you can use Deno.upgradeWebSocket
inside the handler function. Here's an example based on the documentation:
In this code, we check if the request is trying to upgrade to a WebSocket. If it is, we use Deno.upgradeWebSocket
to upgrade the connection and then handle the WebSocket events like onopen
, onmessage
, onerror
, and onclose
.
You can adapt this example to fit into an async generator by yielding the upgraded WebSocket connections. Remember to handle each requestasynchronously to ensure that your server can process multiple requests concurrently.
I hope this helps you set up your server with upgraded WebSocket connections! If you have any more questions or need further assistance, feel free to ask. 🦕
You can yield a WebSocket like this:
I hope it helps