Skip to content

Instantly share code, notes, and snippets.

@kwhinnery
Created August 3, 2023 19:35
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwhinnery/0837be292af5ab3ea1bd62d080735bd1 to your computer and use it in GitHub Desktop.
Save kwhinnery/0837be292af5ab3ea1bd62d080735bd1 to your computer and use it in GitHub Desktop.
A simple link shortener built with Deno. Run with `deno run --allow-net --unstable server.ts`
const kv = await Deno.openKv();
Deno.serve(async (request: Request) => {
// Create short links
if (request.method == "POST") {
const body = await request.text();
const { slug, url } = JSON.parse(body);
const result = await kv.set(["links", slug], url);
return new Response(JSON.stringify(result));
}
// Redirect short links
const slug = request.url.split("/").pop() || "";
const url = (await kv.get(["links", slug])).value as string;
if (url) {
return Response.redirect(url, 301);
} else {
const m = !slug ? "Please provide a slug." : `Slug "${slug}" not found`;
return new Response(m, {
status: 404,
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment