kdocs
GitHub
Lang - Runtime
Lang - Runtime
  • Go
    • Modules & Packages
    • Variables
    • Structs
    • Interfaces
    • Functions
    • Control Structures
    • Erro Handling
    • Concurrency
    • Testing
    • Fuzzing
  • Web
    • V8 Engine
    • Node.js
      • New Project
    • Deno
      • New Project
Powered by GitBook
On this page
  • Web Server
  • Starting the project
  • Serving content
  • Running
  1. Web
  2. Deno

New Project

PreviousDeno

Last updated 4 months ago

Deno has a built in HTTP server API that allows you to write HTTP/1.1 and HTTP/2 servers.

Starting the project

deno init <project_name>

VSCode

Inside VSCode you may want to execute:

Deno: Initialize Workspace Configuration

This will create a .vscode on the project to enable Deno extension to work.

Serving content

HTTP/2 support is "automatic" when using the HTTP server APIs with Deno.

You just need to create your server, and it will handle HTTP/1 or HTTP/2 requests seamlessly.

The HTTP server has built in automatic compression of response bodies. (Supporting gzip and brotli compression)

Check some conditions for this automatic compression .

Simple content

By default Deno will listen on port 8000.

// To listen on port 4242 and bind to 0.0.0.0.
Deno.serve({ port: 4242, hostname: "0.0.0.0" }, (req) => {
    console.log("Method:", req.method);
    
    const url = new URL(req.url);
    console.log("Path:", url.pathname);
    console.log("Query parameters:", url.searchParams);
    
    console.log("Headers:", req.headers);
    
    if (req.body) {
        const body = await req.text();
        console.log("Body:", body);
    }
    
    // Responding a string only
    return new Response('Hello World.');
    
    const data = JSON.stringify({ id: 1, name: 'Marco', ... });
    return new Response(data, {
        status: 200,
        headers: {
            "content-type": "application/json; charset=utf-8",
        },
    });
});

req.text() call and ALL other methods that read from the Request Body can fail if the user hangs up the connection before the body is fully received.

Make sure to handle this case.

For HTTPS make sure to add two more parameters.

Deno.serve({
    port: 443,
    cert: Deno.readTextFileSync("./cert.pem"),
    key: Deno.readTextFileSync("./key.pem"),
}, handler);

Streaming content

Deno can upgrade incoming HTTP requests to a WebSocket.

Note that WebSockets are only supported on HTTP/1.1 for now.

Running

Don't forget to give the --allow-net permissions.

deno run --allow-net server.ts

Check an example .

Web Server
here
here
Websockets