在 CF Workers 搭建自己的 t.cn 短网址入口

基于 Cloudflare Workers 的在线版页面,创建个 workers 把以下代码粘贴进去就可以了,快把今天撸的免费域名用起来吧!

addEventListener('fetch', (event) => {
  return event.respondWith(handleRequest(event.request));
})

const handleRequest = async (request) => {
  const render = (body) => {
    return new Response(`
      <!doctype html>
      <html>
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <title>T.CN 短网址</title>
      </head>
      <body>${body}</body>
      </html>`.trim(), {
      status: 200,
      headers: {
        'Content-Type': 'text/html; charset=utf-8'
      }
    });
  }
  request = new URL(request.url);
  if (request.pathname !== '/') return new Response(null, { status: 404 });
  if (request.searchParams.has('url')) {
    const url = request.searchParams.get('url');
    const response = await fetch(`http://service.weibo.com/share/share.php?url=${encodeURIComponent(url)}&title=1`);
    const html = await response.text();
    const short = html.match(/http:\/\/t.cn\/\w+/i);
    const refer = html.match(/\$refer\s+: "(.+?)"/i);
    if (short && refer) {
      return render(`
        缩短结果:<a href="${short[0]}">${short[0]}</a><br />
        原始网址:<a href="${refer[1]}">${refer[1]}</a><br />
        <a href="/">返回</a>
      `);
    }
    return render(`请求失败`);
  }
  return render(`
    <form method="GET">
    <input name="url" placeholder="URL" />
    <button type="submit">压缩</button>
    </form>
  `);
}

演示网址:

https://url.cmsblog.workers.dev/

© 版权声明
THE END
点赞0赞赏 分享
评论 共2条
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片
    • admin的头像-爱学习admin等级-LV1-爱学习作者0