Last active
November 28, 2025 19:54
-
-
Save ggondim/7cfc3a9f76aa8e3392065a704244724e to your computer and use it in GitHub Desktop.
SINGLE BUN SERVER: Server entry point for Bun runtime.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * SINGLE BUN SERVER | |
| * Server entry point for Bun runtime. | |
| * © 2025 Gustavo Gondim | |
| * MIT License | |
| * | |
| * Sets up a simple HTTP server that listens for requests to a single route | |
| * and method (configurable via environment variables) and delegates request | |
| * handling to a shared handler function. | |
| * | |
| * This server file is intended to be minimal. Complex routing or middleware | |
| * can be added by integrating with a more full-featured framework if needed, | |
| * using the fetch function as middleware. | |
| * | |
| * Additional parameter/endpoint validation related to the operation | |
| * should be performed in the handler to keep this server file simple and | |
| * focused on server setup. | |
| * | |
| * Defaults: | |
| * - Port: 3000 (configurable via PORT env var) | |
| * - Pathname: / (configurable via SERVER_HTTP_PATHNAME env var) | |
| * - Method: POST (configurable via SERVER_HTTP_METHOD env var) | |
| */ | |
| // REPLACE with your actual handler import | |
| import { yourHandlerFunction } from "./path/to/yourHandlerFile"; | |
| // Minimal Bun detection: this project targets the Bun runtime. | |
| // If Bun is not present or does not expose `serve`, fail early. | |
| type BunLike = { serve?: (opts: unknown) => void }; | |
| const bun = (globalThis as unknown as { Bun?: BunLike }).Bun; | |
| if (!bun || typeof bun.serve !== "function") { | |
| throw new Error("This server must run on Bun."); | |
| } | |
| const port = parseInt(process.env.PORT || "3000", 10); | |
| const PATHNAME = process.env.SERVER_HTTP_PATHNAME || "/"; | |
| const METHOD = process.env.SERVER_HTTP_METHOD || "POST"; | |
| bun.serve({ | |
| port, | |
| // Simple router wrapper: validate method/path here so the handler | |
| // remains agnostic and can be reused as middleware by other frameworks. | |
| fetch: async (req: Request) => { | |
| try { | |
| const url = new URL(req.url); | |
| if (req.method !== METHOD || url.pathname !== PATHNAME) { | |
| return new Response("Not found", { status: 404 }); | |
| } | |
| return await handleFetch(req); | |
| } catch (err: unknown) { | |
| const msg = err instanceof Error ? err.message : String(err); | |
| return new Response(msg, { status: 500 }); | |
| } | |
| }, | |
| }); | |
| console.log(`Server listening on http://0.0.0.0:${port}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment