抱脸国内访问速度慢,上面部署的Open WebUI访问起来经常卡顿,原因是Open WebUI比较重,静态资源比较大,在访问速度慢的情况下加载时间特别长,导致经常卡LOGO,甚至有时聊天都会卡,而用deno反代就可以很好的解决这个问题。至于为什么不用CF Workers,原因是它好像对反代的限制也越来越严了,反代Open WebUI这种比较重的项目,动不动就会报错。
下面是deno反代的源码
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { parse } from "https://deno.land/[email protected]/flags/mod.ts";
const DEFAULT_PORT = 8080;
const TARGET_HOST = "open-webui-open-webui.hf.space";
function log(message: string) {
console.log(`[${new Date().toISOString()}] ${message}`);
}
function getDefaultUserAgent(isMobile: boolean = false): string {
if (isMobile) {
return "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36";
} else {
return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";
}
}
function transformHeaders(headers: Headers): Headers {
const isMobile = headers.get("sec-ch-ua-mobile") === "?1";
const newHeaders = new Headers();
for (const [key, value] of headers.entries()) {
newHeaders.set(key, value);
}
newHeaders.set("User-Agent", getDefaultUserAgent(isMobile));
newHeaders.set("Host", TARGET_HOST);
newHeaders.set("Origin", `https://${TARGET_HOST}`);
return newHeaders;
}
async function handleRequest(req: Request): Promise<Response> {
try {
const url = new URL(req.url);
const targetUrl = `https://${TARGET_HOST}${url.pathname}${url.search}`;
log(`Proxying request: ${targetUrl}`);
const proxyReq = new Request(targetUrl, {
method: req.method,
headers: transformHeaders(req.headers),
body: req.body,
redirect: "follow",
});
const response = await fetch(proxyReq);
const responseHeaders = new Headers(response.headers);
responseHeaders.set("Access-Control-Allow-Origin", "*");
return new Response(response.body, {
status: response.status,
headers: responseHeaders,
});
} catch (error) {
log(`Error: ${error.message}`);
return new Response(`Proxy Error: ${error.message}`, { status: 500 });
}
}
async function startServer(port: number) {
log(`Starting proxy server on port ${port}`);
await serve(handleRequest, {
port,
onListen: () => {
log(`Listening on http://localhost:${port}`);
},
});
}
if (import.meta.main) {
const { args } = Deno;
const parsedArgs = parse(args);
const port = parsedArgs.port ? Number(parsedArgs.port) : DEFAULT_PORT;
startServer(port);
}
注意
我这里设置的是反代Open WebUI的官方的抱脸空间,使用时请把代码第四行的open-webui-open-webui.hf.space
替换成你自己的抱脸空间域名