A small, extensible HTTP server.
For further insights, read on.
To install this library use your favorite package manager. No additional steps are required to start using the library.
npm install @n7e/http-server
This library is implemented in TypeScript but can be used with JavaScript without any additional steps.
A server instance takes care of incoming HTTP requests, delegating them to a request handler and serving the responses.
Server
is just an interface describing the functionality of an HTTP server.
To create a server instance use a server builder.
To configure and build a server instance you should use a ServerBuilder
.
import { ServerBuilder } from "@n7e/http-server";
function doSomethingWith(serverBuilder: ServerBuilder): void {
const server = serverBuilder
.useRequestHandler(requestHandler)
.usePort(80)
.build();
// ...
}
ServerBuilder
is just an interface describing the functionality of a server
builder. To create a server builder instance you need to reference a specific
implementation.
There's a provided default implementation of ServerBuilder
ready to use. The
implementation depends on a RequestFactory
and a ResponseFactory
. Since the
@n7e/http
library provides default implementations here's an example of how to
create a server builder:
import { DefaultRequestFactory, DefaultResponseFactory, DefaultStreamFactory, DefaultUriFactory } from "@n7e/http";
import { DefaultServerBuilder } from "@n7e/http-server";
const serverBuilder = new DefaultServerBuilder(
new DefaultRequestFactory(new DefaultUriFactory()),
new DefaultResponseFactory(new DefaultStreamFactory())
);
All incoming requests are delegated to a dedicated request handler. There are two request handler implementations provided:
- DefaultRequestHandler
-
Simply responds with 503 Service Unavailable.
(This is the default request handler) - MiddlewareRequestHandler
- Processes incoming requests through a set of registered middleware.
import { MiddlewareRequestHandler } from "@n7e/http-server";
serverBuilder.useRequestHandler(new MiddlewareRequestHandler(new Set()));
If no middleware produce a response an exception will be thrown causing the server to respond with 500 Internal Server Error.