Jasmine Boba'tea
Jasmine Boba'tea•3w ago

What is the best way to get the full url that Deno.serve() is running on?

If I have:
Deno.serve(
{ port: 1993, hostname: '0.0.0.0' },
(_req) => new Response("Hello, world")
);
Deno.serve(
{ port: 1993, hostname: '0.0.0.0' },
(_req) => new Response("Hello, world")
);
I know the url will be: http://0.0.0.0:1993 . Is there something in the Deno.* API that I can reference to get it though?
4 Replies
gabe
gabe•3w ago
yes, the handler (second parameter to Deno.serve() ) is a function that receives 2 parameters: requestand info: - serve docs: https://docs.deno.com/api/deno/~/Deno.serve#function_serve_2 - ServeHandler type definition: https://docs.deno.com/api/deno/~/Deno.ServeHandler try this:
Deno.serve(
{ port: 1993, hostname: '0.0.0.0' },
(_req, info) => {
console.log(info);
return new Response("Hello, world");
}
);
Deno.serve(
{ port: 1993, hostname: '0.0.0.0' },
(_req, info) => {
console.log(info);
return new Response("Hello, world");
}
);
Fifth-Normal-Form
Fifth-Normal-Form•3w ago
You can also get it from the request:
Deno.serve({ port: 1993, hostname: '0.0.0.0'},
(request: Request) => {
const url = new URL(request.url)
return new Response(`
Hello From:
origin = ${url.origin}
host = ${url.host}
hostname = ${url.hostname}
port = ${url.port}
transport protocol = ${url.protocol}:
`)
})
Deno.serve({ port: 1993, hostname: '0.0.0.0'},
(request: Request) => {
const url = new URL(request.url)
return new Response(`
Hello From:
origin = ${url.origin}
host = ${url.host}
hostname = ${url.hostname}
port = ${url.port}
transport protocol = ${url.protocol}:
`)
})
I'm on Widows where 0.0.0.0 === localhost.
Hello From:
origin = http://localhost:1993
host = localhost:1993
hostname = localhost
port = 1993
transport protocol = http:
Hello From:
origin = http://localhost:1993
host = localhost:1993
hostname = localhost
port = 1993
transport protocol = http:
If I then open 127.0.0.2 :1993 as expected:
Hello From:
origin = http://127.0.0.2:1993
host = 127.0.0.2:1993
hostname = 127.0.0.2
port = 1993
transport protocol = http:
Hello From:
origin = http://127.0.0.2:1993
host = 127.0.0.2:1993
hostname = 127.0.0.2
port = 1993
transport protocol = http:
Logging info on Windows returns an empty object?
ServeHandlerInfo {}
ServeHandlerInfo {}
With either console.log(info) or, console.info(info)?
Jasmine Boba'tea
Jasmine Boba'teaOP•3w ago
Thanks all! This is extremely helpful 🙂
YousefShanawany
YousefShanawany•3w ago
I honestly just store these as environment variables since they differ per environment.

Did you find this page helpful?