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

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>
  `);
}

Leave a Comment