Skip to content

Instantly share code, notes, and snippets.

@ChangJoo-Park
Last active February 6, 2021 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChangJoo-Park/145d3f99743dda694ecd4f713b1dcf87 to your computer and use it in GitHub Desktop.
Save ChangJoo-Park/145d3f99743dda694ecd4f713b1dcf87 to your computer and use it in GitHub Desktop.
Simple Deno API Server using standard library
import {
listenAndServe,
ServerRequest,
} from "https://deno.land/std/http/server.ts";
const options: Deno.ListenOptions = { port: 8000 };
class Router {
_get: { [k: string]: (req: ServerRequest) => void } = {};
get(path: string, handler: (req: ServerRequest) => void) {
this._get[path] = handler;
}
route(req: ServerRequest) {
if (this._get[req.url]) {
return this._get[req.url](req);
}
return req.respond({
status: 404,
body: JSON.stringify({ message: "NOT FOUND" }),
});
}
}
const router = new Router();
router.get(
"/",
(req: ServerRequest) =>
req.respond({ status: 200, body: JSON.stringify({ message: "Index" }) }),
);
router.get(
"/hello",
(req: ServerRequest) =>
req.respond({ status: 200, body: JSON.stringify({ message: "Hello" }) }),
);
listenAndServe(options, ((req: ServerRequest) => router.route(req)));
import {
listenAndServe,
ServerRequest,
} from "https://deno.land/std/http/server.ts";
const options: Deno.ListenOptions = { port: 8000 };
const handler = (req: ServerRequest) =>
req.respond({ status: 200, body: "Hello World" });
listenAndServe(options, handler);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment