forked from adams549659584/go-proxy-bingai
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
worker.js
64 lines (62 loc) · 2 KB
/
worker.js
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
import { CUSTOM_OPTIONS,init_CUSTOM_OPTIONS } from "./src/OPTIONS"
import { workerFetch } from './src/worker'
import { rewriteBody } from "./src/rewriteBody.js"
export default {
/**
* fetch
* @param {Request} request
* @param {*} env
* @param {*} ctx
* @returns
*/
async fetch(request, env, ctx) {
init_CUSTOM_OPTIONS(env);
const currentUrl = new URL(request.url);
if (currentUrl.pathname === '/' || currentUrl.pathname.indexOf('/web/') === 0) {
return home(currentUrl.pathname);
}
return workerFetch(request, env, ctx);
}
}
/**
* home
* @param {string} pathname
* @returns
*/
async function home(pathname){
let baseUrl;
if (CUSTOM_OPTIONS.NIGHTLY) {
baseUrl = 'https://raw.githubusercontent.com/Harry-zklcdc/go-proxy-bingai/nightly/';
} else {
baseUrl = 'https://raw.githubusercontent.com/Harry-zklcdc/go-proxy-bingai/master/';
}
let url;
if (pathname.indexOf('/web/') === 0) {
url = pathname.replace('/web/', baseUrl + 'web/');
if (pathname == '/web/') {
url += 'index.html';
}
} else {
let res = new Response('', {
status: 302,
});
res.headers.set("location", "/web/");
return res;
}
const res = await fetch(url);
const result = await rewriteBody(res);
const newRes = new Response(result.body, res);
if (pathname.endsWith('.js')) {
newRes.headers.set('content-type', 'application/javascript');
} else if (pathname.endsWith('.css')) {
newRes.headers.set('content-type', 'text/css');
} else if (pathname.endsWith('.svg')) {
newRes.headers.set('content-type', 'image/svg+xml');
} else if (pathname.endsWith('.ico') || pathname.endsWith('.png')) {
newRes.headers.set('content-type', 'image/png');
} else {
newRes.headers.set('content-type', 'text/html; charset=utf-8');
}
newRes.headers.delete('content-security-policy');
return newRes;
};