With Deno.serveHttp marked as deprecated is there a way to run an HTTP server off of a Deno.Conn?
I have a bit of weird use-case where I want to start a listener, accept the first TCP connection (and serve HTTP to it) and then reject all future TCP connections.
I have the following code:
Is there a way to do this using Deno.serve, or something else?
7 Replies
The documentation indicates that
Deno.serveHttp()
is indeed used to handle HTTP requests and responses on a connection. It returns a Deno.HttpConn
, which is an async iterable that yields Deno.RequestEvent
objects for each HTTP request that the connection receives.
Your use case, where you want to accept the first TCP connection to serve HTTP and then reject all future TCP connections, is supported by the Deno.serveHttp()
function. Your current code snippet is correctly using Deno.serveHttp()
to serve HTTP over the first accepted connection and then closes any subsequent connections.
As for using Deno.serve
, it is a higher-level API that abstracts away the details of creating a listener and directly serves HTTP. However, it does not provide the same level of control over individual connections as manually creating a listener and using Deno.serveHttp()
does.
Given your specific requirement to accept only the first connection and reject others, continuing to use Deno.serveHttp()
as you are currently doing is the appropriate approach. There is no need to switch to Deno.serve
unless you want to simplify your code and do not need to manage individual TCP connections.
Here is a simplified version of your code that demonstrates the intended behavior using Deno.serveHttp()
:
In this example, after serving HTTP on the first connection, the server is closed, which will prevent any new connections from beingaccepted. This aligns with your requirement to serve only the first connection. 🦕
The AI is helpful but seems less afraid of the looming 2.0 soft removal
@mmastrac any suggestion here?
I think we should probably add a
Deno.serveOn
API, but in the meantime you could accept the connection manually and proxy it to your internal Deno.serve
listener that is listening only locally.
I have a feeling Deno.serveHttp
will be around for a while, so I wouldn't be too afraid of using it. We don't have a specific removal date for that API and it's pretty heavily used.ok, sounds good, thanks. I am a little sensitive to the overhead of spawning another connection to proxy to Deno.serve, but will keep using serveHttp for now. Would be very interested in a
Deno.serveOn
api.I also have this usecase, when I'm requesting user consent for accessing google account.
So were there any solutions to a one-off serving?
My code btw:
I modified it, but needs an extra
setTimeout
for server.shutdown, of throws an error