Skip to main content
Deno 2 is finally here 🎉️
Learn more

http-websocket

deno land deno doc GitHub

HTTP request for websocket with standard Request and Response.

HTTP handler for websocket

Create WebSocket request handler.

import {
  createHandler,
  SocketHandler,
} from "https://deno.land/x/http_websocket@$VERSION/mod.ts";
import { serve } from "https://deno.land/std@$VERSION/http/mod.ts";
const socketHandler: SocketHandler = (socket) => {
  socket.onopen = () => {
    socket.send("hello");
  };
};
const handler = createHandler(socketHandler);
await serve(handler);

Spec

The Response includes status code and headers as follow:

Code Headers
101
400
405 allow
500

WebSocket Status Code and Status Text

Helper for processing status code and status text.

import {
  Status,
  STATUS_TEXT,
} from "https://deno.land/x/http_websocket@$VERSION/mod.ts";
import { assertEquals } from "https://deno.land/std@$VERSION/testing/asserts.ts";

assertEquals(Status.NormalClosure, 1000);
assertEquals(STATUS_TEXT[Status.NormalClosure], "Normal Closure");

Validate request

HTTP request validation for websocket. The validation is based on RFC 6455, 4.1.

The result of the validation is returned as a tuple. If there is an error, the second element is HttpError.

import {
  validateRequest,
} from "https://deno.land/x/http_websocket@$VERSION/mod.ts";
import {
  assertEquals,
  assertIsError,
} from "https://deno.land/std@$VERSION/testing/asserts.ts";

const req = new Request("http://localhost/");
const result = validateRequest(req);
assertEquals(result[0], false);
assertIsError(result[1]);

License

Copyright © 2022-present httpland.

Released under the MIT license