Skip to content

Instantly share code, notes, and snippets.

@mayankchoubey
Last active January 3, 2022 07:11
Show Gist options
  • Save mayankchoubey/c3e4513d108c92de22ee02eba3d6bfeb to your computer and use it in GitHub Desktop.
Save mayankchoubey/c3e4513d108c92de22ee02eba3d6bfeb to your computer and use it in GitHub Desktop.
A beginner HTTP server in Deno
import { serve } from "https://deno.land/std/http/mod.ts";
async function reqHandler(req: Request) {
if (
!req.headers.has("Authorization") ||
req.headers.get("Authorization")?.split(" ")[1] !==
Deno.env.get("AUTH_TOKEN")
) {
return new Response(null, { status: 401 });
}
if (req.method !== "POST") {
return new Response(null, { status: 405 });
}
const { pathname: path, searchParams: query } = new URL(req.url);
if (path !== "/users/search") {
return new Response(null, { status: 404 });
}
let userId;
if (
req.headers.has("content-type") &&
req.headers.get("content-type")?.startsWith("application/json") &&
req.body
) {
userId = (await req.json()).userId;
}
if (!userId) {
userId = query.get("userId");
}
if (!userId) {
return new Response(null, { status: 400 });
}
const userObj = JSON.parse(await Deno.readTextFile("./db.json"))[userId];
if (!userObj) {
return new Response(null, { status: 204 });
}
return new Response(JSON.stringify(userObj), {
headers: {
"content-type": "application/json; charset=UTF-8",
},
});
});
serve(reqHandler, { port: 5000 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment