From 3a3b85f138852b5059c75afbea115bc75f12d547 Mon Sep 17 00:00:00 2001 From: Alexander Zinn Date: Fri, 21 Nov 2025 03:15:34 -0500 Subject: [PATCH] Enhance BunHttpServer with port configuration and server management * Added a private _port property to manage the server port. * Updated constructor to accept a BunServer instance. * Implemented listen method to start the Bun server with specified configurations. * Introduced stop method to gracefully stop the Bun server. --- src/net/http/BunHttpServer.ts | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/net/http/BunHttpServer.ts b/src/net/http/BunHttpServer.ts index a399119..a57b558 100644 --- a/src/net/http/BunHttpServer.ts +++ b/src/net/http/BunHttpServer.ts @@ -16,11 +16,16 @@ export class BunHttpServer { private readonly _logger = LoggerFactory.getLogger('BunHttpServer'); private readonly _webSocketHandler: WebSocketHandler | undefined; private readonly _routes: BunRoutes; + private _port: number = 5000; + private _bunServer: BunServer | undefined; - constructor(routes: BunRoutes, webSocketHandler: WebSocketHandler | undefined) { + constructor(routes: BunRoutes, webSocketHandler: WebSocketHandler | undefined, bunServer: BunServer) { this._routes = routes; this._webSocketHandler = webSocketHandler; - this.fetch = this.fetch.bind(this); + } + + get port(): number { + return this._port; } get websocket(): WebSocketHandler | undefined { @@ -31,15 +36,26 @@ export class BunHttpServer { return this._routes; } - public addRoute(path: string, handler: BunRouteHandler): void { - if (this._routes[path]) { - throw new Error(`Route [${path}] already exists`); - } + public listen(port: number): Promise { + this._port = port; - this._routes[path] = handler.bind(this); + return new Promise((resolve) => { + this._bunServer = Bun.serve({ + fetch: this.fetch.bind(this), + port: this._port, + hostname: '0.0.0.0', + websocket: this._webSocketHandler, + routes: this._routes + }); + resolve(); + }); + } + + public stop(): void { + this._bunServer?.stop(); } - public async fetch(request: BunRequest, server: BunServer): Promise { + private async fetch(request: BunRequest, server: BunServer): Promise { const url = new globalThis.URL(request.url); this._logger.info('Received [%s] request from [%s] for unknown route [%s]', request.method, server.requestIP(request)?.address ?? 'unknown', url.pathname);