Last active
February 6, 2021 15:39
-
-
Save ChangJoo-Park/145d3f99743dda694ecd4f713b1dcf87 to your computer and use it in GitHub Desktop.
Simple Deno API Server using standard library
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
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))); |
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
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