├── LICENSE
├── README.md
└── cloudflare-worker.js
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Barret李靖
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # cloudflare-proxy
2 |
3 | > 好多调用 ChatGPT 的客户端都是直接使用的 api.openai.com,这个接口很显然是访问不通的,好在有些良心作者还提供了一个自定义 API 域名的入口,在 Cloudflare Worker 上写了一个简单的代理,用起来顺手多了,省得我一直在本机挂全局代理。—— [Barret李靖](https://twitter.com/Barret_China/status/1642725620798087168)
4 |
5 |
6 |
7 |
8 | 代理请求到 ChatGPT API,代码部署步骤:
9 |
10 | 1. 注册并登录到 Cloudflare 账户
11 | 2. 创建一个新的 Cloudflare Worker
12 | 3. 将 [cloudflare-worker.js](./cloudflare-worker.js) 复制并粘贴到 Cloudflare Worker 编辑器中
13 | 4. 保存并部署 Cloudflare Worker
14 | 5. 在 Worker 详情页 -> Trigger -> Custom Domains 中为这个 Worker 添加一个自定义域名
15 |
16 | 为啥需要第五步?因为直接使用 Cloudflare 的域名,依然无法访问。
17 |
18 |
19 |
20 | ### 使用说明
21 |
22 | ChatGPT 的 API 默认是非流式输出的,如果想让他变成流式输出,需要将 `payload.stream` 设置为 true,大部分的客户端都已经加上了这个参数。
23 |
24 | https://github.com/barretlee/cloudflare-proxy/blob/a7cf8ecfd3eed5c4d76f82f4f4387ed4ef39c6f3/cloudflare-worker.js#L36-L50
25 |
26 | ### License
27 |
28 | [MIT](./LICENSE)
29 |
--------------------------------------------------------------------------------
/cloudflare-worker.js:
--------------------------------------------------------------------------------
1 | addEventListener("fetch", (event) => {
2 | event.respondWith(handleRequest(event.request));
3 | });
4 |
5 | async function handleRequest(request) {
6 | const url = new URL(request.url);
7 | const fetchAPI = request.url.replace(url.host, 'api.openai.com');
8 |
9 | // 部分代理工具,请求由浏览器发起,跨域请求时会先发送一个 preflight 进行检查,也就是 OPTIONS 请求
10 | // 需要响应该请求,否则后续的 POST 会失败
11 | const corsHeaders = {
12 | 'Access-Control-Allow-Origin': '*',
13 | 'Access-Control-Allow-Methods': 'OPTIONS',
14 | 'Access-Control-Allow-Headers': '*',
15 | };
16 | if (request.method === 'OPTIONS') return new Response(null, { headers: corsHeaders });
17 |
18 | const authKey = request.headers.get('Authorization');
19 | if (!authKey) return new Response("Not allowed", { status: 403 });
20 |
21 | let contentType = request.headers.get('Content-Type')
22 | if (contentType && contentType.startsWith("multipart/form-data")) {
23 | let newRequest = new Request(fetchAPI, request);
24 | return await fetch(newRequest);
25 | }
26 |
27 | let body;
28 | if (request.method === 'POST') body = await request.json();
29 |
30 | const payload = {
31 | method: request.method,
32 | headers: {
33 | "Content-Type": "application/json",
34 | Authorization: authKey,
35 | },
36 | body: typeof body === 'object' ? JSON.stringify(body) : '{}',
37 | };
38 | // 在 Cloudflare 中,HEAD 和 GET 请求带 body 会报错
39 | if (['HEAD', 'GET'].includes(request.method)) delete payload.body;
40 |
41 | // 入参中如果包含了 stream=true,则表现形式为流式输出
42 | const response = await fetch(fetchAPI, payload);
43 | if (body && body.stream !== true) {
44 | const results = await response.json();
45 | return new Response(JSON.stringify(results), {
46 | status: response.status,
47 | headers: {
48 | "Content-Type": "application/json",
49 | },
50 | });
51 | } else {
52 | return new Response(response.body, {
53 | status: response.status,
54 | statusText: response.statusText,
55 | headers: response.headers,
56 | });
57 | }
58 | }
59 |
--------------------------------------------------------------------------------