文章

白嫖 CloudFlare 服务之 Workers

白嫖 CloudFlare 服务之 Workers

CloudFlare Workers 是 CloudFlare 提供的一种无服务器计算平台,允许开发者在 CloudFlare 的边缘网络上运行 JavaScript 代码。它可以用于处理 HTTP 请求、修改响应、与其他 API 交互等。

由于其高效的性能和灵活性,CloudFlare Workers 可以无需自备服务器即可实现很多功能。

轻松搭建简单的后端

对于需求不大,任务简单的用户来说,CloudFlare Workers 可以用来搭建后端,例如处理静态资源的请求等。

由于开发 CardRecord (Raccon-Script) 时发现数据硬编码到脚本里会对用户带来不便,因此决定使用 CloudFlare Workers 来搭建一个简单的后端服务,提供数据接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 简易的 mob 数据表
const mobValues = {
  "Black Hole": -1,
  Ghost: -0.5,
  //其余数据略
};

// Worker 入口
export default {
  async fetch(request) {
    const { searchParams } = new URL(request.url);
    const mob = searchParams.get("mob");

    const corsHeaders = {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, OPTIONS",
      "Access-Control-Allow-Headers": "Content-Type",
    };

    // 处理预检请求 (OPTIONS)
    if (request.method === "OPTIONS") {
      return new Response(null, { headers: corsHeaders });
    }

    if (mob) {
      const value = mobValues[mob] ?? 0;
      return new Response(JSON.stringify({ mob, value }), {
        headers: {
          "Content-Type": "application/json",
          ...corsHeaders,
        },
      });
    }

    return new Response(JSON.stringify(mobValues, null, 2), {
      headers: {
        "Content-Type": "application/json",
        ...corsHeaders,
      },
    });
  },
};

反向代理

Workers 可以做反向代理,制作镜像网站,同时非常灵活地处理请求和响应。

为了保证我博客的访问速度,同样使用 CloudFlare Workers 反向代理,对国内用户将 jsdelivr.net 替换为 jsd.onmicrosoft.cn:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});

const CONFIG = {
  ALLOWED_HOSTNAME: "blog-cn.davidx.app",
  ORIGIN_HOSTNAME: "blog-zh.pages.dev",
  REPLACE_RULES: {
    "cdn.jsdelivr.net": "jsd.onmicrosoft.cn",
  },
  IMAGE_EXTENSIONS: [".jpg", ".jpeg", ".png", ".gif", ".svg", ".webp", ".ico"],
};

async function handleRequest(request) {
  const url = new URL(request.url);

  if (url.hostname !== CONFIG.ALLOWED_HOSTNAME) {
    return new Response("Invalid hostname", { status: 403 });
  }

  let originHost = `${CONFIG.ORIGIN_HOSTNAME}`;
  let pathname = url.pathname;

  const fetchUrl = `https://${originHost}${pathname}${url.search}`;

  try {
    let response = await fetch(fetchUrl, {
      method: request.method,
      headers: request.headers,
    });

    // 检查是否为图片请求
    const isImage = CONFIG.IMAGE_EXTENSIONS.some((ext) =>
      url.pathname.toLowerCase().endsWith(ext),
    );

    if (isImage) {
      // 图片请求直接返回二进制数据
      const newResponse = new Response(response.body, {
        status: response.status,
        statusText: response.statusText,
        headers: response.headers,
      });
      newResponse.headers.set("Access-Control-Allow-Origin", "*");
      newResponse.headers.set("Cache-Control", "public, max-age=86400");
      return newResponse;
    }

    // 非图片请求保持原有处理逻辑
    let body = await response.text();

    const countryCode = request.cf.country;
    if (countryCode === "CN") {
      // 替换资源域名
      for (const [from, to] of Object.entries(CONFIG.REPLACE_RULES)) {
        body = body.replaceAll(from, to);
      }
    }

    body = body.replaceAll(
      `${CONFIG.ORIGIN_HOSTNAME}`,
      `${CONFIG.ALLOWED_HOSTNAME}`,
    );

    // 构建新响应
    const newResponse = new Response(body, {
      status: response.status,
      statusText: response.statusText,
      headers: response.headers,
    });

    // 设置响应头
    newResponse.headers.set("Access-Control-Allow-Origin", "*");
    newResponse.headers.set("Cache-Control", "public, max-age=3600");

    return newResponse;
  } catch (err) {
    return new Response("Error: " + err.message, { status: 500 });
  }
}

自动化监控

自动化监控网站运转情况,参考 UptimeFlare。(不是我自己写的项目,不太懂,但确实很好用)

本文由作者按照 CC BY 4.0 进行授权