Skip to content

Instantly share code, notes, and snippets.

@dcgauld
Last active June 2, 2020 09:12
Show Gist options
  • Save dcgauld/205218530e8befe4dfc20ade54e7cc84 to your computer and use it in GitHub Desktop.
Save dcgauld/205218530e8befe4dfc20ade54e7cc84 to your computer and use it in GitHub Desktop.
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