Skip to content

CloudFlare Worker + KV namespace来实现URL Shortener

参考这里 – https://github.com/xyTom/Url-Shorten-Worker

新增KV name space

新增Worker

找到 https://github.com/lava-lake/Url-Shorten-Worker/blob/main/index.js

const html404 = `<!DOCTYPE html>
<body>
  <h1>404 Not Find.</h1>
  <p>The url you visit is not find.</p>
</body>`


async function randomString(len) {
  len = len || 6;
  let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  let maxPos = $chars.length;
  let result = '';
  for (i = 0; i < len; i++) {
    result += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return result;
}
async function checkURL(URL){
    let str=URL;
    let Expression=/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
    let objExp=new RegExp(Expression);
    if(objExp.test(str)==true){
      if (str[0] == 'h')
        return true;
      else
        return false;
    }else{
        return false;
    }
} 
async function save_url(URL){
    let random_key=await randomString()
    let is_exist=await LINKS.get(random_key)
    console.log(is_exist)
    if (is_exist == null)
        return await LINKS.put(random_key, URL),random_key
    else
        save_url(URL)
}
async function handleRequest(request) {
  console.log(request)
  if (request.method === "POST") {
    let req=await request.json()
    console.log(req["url"])
    if(!await checkURL(req["url"]))
    return new Response(`{"status":500,"key":": Error: Url illegal."}`)
    let stat,random_key=await save_url(req["url"])
    console.log(stat)
    if (typeof(stat) == "undefined")
      return new Response(`{"status":200,"key":"/`+random_key+`"}`)
    else
      return new Response(`{"status":200,"key":": Error:Reach the KV write limitation."}`)
  }

  const requestURL = new URL(request.url)
  const path = requestURL.pathname.split("/")[1]
  console.log(path)
  if(!path){

    const html= await fetch("https://xytom.github.io/Url-Shorten-Worker/")
    
    return new Response(await html.text(), {
    headers: {
      "content-type": "text/html;charset=UTF-8",
    },
  })
  }
  const value = await LINKS.get(path)
  console.log(value)
  

  const location = value
  if (location) {
    return Response.redirect(location, 302)
    
  }
  // If request not in kv, return 404
  return new Response(html404, {
    headers: {
      "content-type": "text/html;charset=UTF-8",
    },
    status: 404
  })
}



addEventListener("fetch", async event => {
  event.respondWith(handleRequest(event.request))
})

将KV namespace绑定到Worker

Add Route – lk.ck.mk/* -> worker url

设定新域名 – lk.ck.mk

访问验证 – lk.ck.mk/tfRBiR

1 thought on “CloudFlare Worker + KV namespace来实现URL Shortener”

Leave a Reply

Your email address will not be published.