Skip to content

Instantly share code, notes, and snippets.

@TonyPepeBear
Created June 22, 2022 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TonyPepeBear/f435dae11b83fc2626a49a6b3cc9848b to your computer and use it in GitHub Desktop.
Save TonyPepeBear/f435dae11b83fc2626a49a6b3cc9848b to your computer and use it in GitHub Desktop.
import { Router } from "itty-router";
const router = Router();
router.get("/", async (req, env) => {
return new Response("Hello Workers", {
status: 200,
});
});
/* new short example json
{
url: "https://tonypepe.com",
len: 3,
}
*/
router.post("/new", async (req, env) => {
const body = await req.json();
console.log(JSON.stringify(body));
var { url, len } = body;
if (url == undefined) return f00("");
if (!isValidHttpUrl(url)) return f00("URL is not valid");
if (len == undefined) len = 5;
if (len < 4) return f00("Lenght must be at least 4");
var s = getRandomString(len);
while ((await env.URLS.get(s)) != undefined) {
len++;
s = getRandomString(len);
}
await env.URLS.put(s, url);
return new Response(s);
});
router.get("/:path", async (req, env) => {
const { params } = req;
const url = await env.URLS.get(params.path.toLowerCase());
if (url == undefined) return new Response("NOT FOUND", { status: 404 });
const response = new Response("", { status: 303 });
response.headers.append("Location", url);
return response;
});
router.get("*", async (req, env) => {
return new Response("404", { status: 404 });
});
export default {
fetch: router.handle,
};
const f00 = (msg) => new Response(msg ? msg : "BAD REQUEST", { status: 400 });
const getRandomInt = (max) => Math.floor(Math.random() * max);
function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
function getRandomString(len) {
var s = "";
for (let i = 0; i < len; i++) {
s += String.fromCharCode(getRandomInt(26) + 97);
}
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment