Basic HTTP Service

Service: WebRun HTTP

This example shows how to create a simple HTTP server directly in the browser:

let counter = 0;
const httpHandler = async () => {
  const time = new Date().toISOString();
  return new Response(
    `<html>
  <body>
  <h4>Hello World ${counter++}!</h4>
  <p>Current time: ${time}
  </p>
  </body>
  </html>`,
    {
      headers: {
        "Content-Type": "text/html",
      },
    },
  );
};

The sections below contain step-by-step instructions how to configure this example.

Step 1: Import the library

import * as WebRunHttp from "https://unpkg.com/@statewalker/webrun-http-browser@0.3/dist/index.js";

Step 2: Start a ServiceWorker

In this section we will start a ServiceWorker and open a MessageChannel used to transport requests and responses between the ServiceWorker and this page.

// Open connection to the ServiceWorker delegating calls to this page:
const {
  port, // A MessagePort instance allowing to communicate with the ServiceWorker
  baseUrl, // The URL of the ServiceWorker script.
  // It is used as a basis to create URL of the virtual HTTP endpoint
  // delegating HTTP calls from the service worker to this page.
  close: closeChannel, // This function closes the communication channel.
} = await WebRunHttp.newRemoteRelayChannel();

Step 3: Register the HTTP Handler

In this section we associate the HTTP handler with an endpoint key. This key is used by the ServiceWorker to delegate calls back to the handler.

Note that the handler function (defined at the beginning of this page) uses the standard Fetch Request and Response objects to handle HTTP calls.

// This constant is used as a key for our HTTP service.
const endpointKey = "EXAMPLE-" + Date.now();

// Now we have of our endpoint URL. It contains the service key.
// The ServerWorker instance dispatches calls to the service handler
// by extracting the key from the service URL.
const serviceUrl = new URL(`~${endpointKey}/`, baseUrl);

// Associate the HTTP service with the key.
// The returned function allows to unregister the service
const closeHttpService = await WebRunHttp.initHttpService(httpHandler, {
  key: endpointKey,
  port,
});

Step 4: Visualize the content

The code below shows how to visualize the resulting resource in an iframe:

<iframe src="${serviceUrl}"
  style="
    border: 1px solid #eee; 
    outline: none; 
    width: 100%;
    height: 100%;
    max-height: 300px;
  "
></iframe>