Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Deno https server

Tags:

deno

I am looking for an example of creating a https server in Deno. I have seen examples of Deno http server but not https.

I have tried searching in google but found no results

like image 251
jayKumar Avatar asked Apr 30 '19 01:04

jayKumar


People also ask

Is Deno for server?

Deno is a V8 JavaScript engine-based runtime built with Rust for JavaScript and TypeScript. And in this tutorial, you'll learn how to use the Deno runtime as an alternative to NodeJS to build an HTTPS server. Read on and start building your server!

Is Deno open source?

Deno is open source software under the MIT License.


2 Answers

With Deno 1.9+ you could use the native server. It provides the ability to use HTTPS.

It is a good bit faster faster than older implementations of std/http. However, as of version 0.107.0 the native server is used for std/http as well.

Example:

const server = Deno.listenTls({
  port: 443,
  certFile: "./my-ca-certificate.pem",
  keyFile: "./my-key.pem"
});

for await (const conn of server) {
  handle(conn);
}

async function handle(conn: Deno.Conn) {
  const httpConn = Deno.serveHttp(conn);
  
  for await (const requestEvent of httpConn) {
    try {
      const response = new Response("Hello World!");
      await requestEvent.respondWith(response);
    } 
    catch (error) {
      console.error(error);
    }
  }
}
like image 190
Zwiers Avatar answered Sep 21 '22 15:09

Zwiers


serveTLS has landed along with Deno 0.23.0:

Sample usage:

import { serveTLS } from "https://deno.land/std/http/server.ts";

const body = new TextEncoder().encode("Hello HTTPS");
const options = {
  hostname: "localhost",
  port: 443,
  certFile: "./path/to/localhost.crt",
  keyFile: "./path/to/localhost.key",
};
// Top-level await supported
for await (const req of serveTLS(options)) {
  req.respond({ body });
}
like image 24
Kevin Qian Avatar answered Sep 20 '22 15:09

Kevin Qian