Skip to content

Instantly share code, notes, and snippets.

@dcgauld

dcgauld/server.ts

Last active Jun 2, 2020
Embed
What would you like to do?
A simple Deno HTTP server.
import {
listenAndServe,
ServerRequest,
} from "https://deno.land/std/http/server.ts";
const { PORT = "8080" } = Deno.env.toObject();
const spuds: Array<string> = [];
const createSpud = async (req: ServerRequest) => {
const decoder = new TextDecoder();
const bodyContents = await Deno.readAll(req.body);
const body = JSON.parse(decoder.decode(bodyContents));
spuds.push(body.type);
req.respond({
status: 201,
});
};
const getSpuds = (req: ServerRequest) => {
const encoder = new TextEncoder();
const body = encoder.encode(JSON.stringify({ spuds }));
req.respond({
body,
headers: new Headers({
"content-type": "application/json",
}),
status: 200,
});
};
const handleRoutes = (req: ServerRequest) => {
if (req.url === "/spuds") {
switch (req.method) {
case "POST":
createSpud(req);
return;
case "GET":
getSpuds(req);
return;
}
}
req.respond({ status: 404 });
};
listenAndServe({ port: parseInt(PORT, 10) }, async (req: ServerRequest) => {
try {
handleRoutes(req);
} catch (error) {
console.log(error);
req.respond({ status: 500 });
}
});
console.log(`Listening on port ${PORT}.`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.