Created
August 3, 2023 19:35
-
-
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`
This file contains 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
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