init: CryptoCoin desktop ticker
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
69
cryptocoin-binance-proxy/src/index.js
Normal file
69
cryptocoin-binance-proxy/src/index.js
Normal file
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* CryptoCoin Binance API 反向代理
|
||||
* 将 /api/v3/... 转发到 https://api.binance.com/api/v3/...
|
||||
*/
|
||||
const BINANCE_ORIGIN = "https://api.binance.com";
|
||||
const ALLOWED_PREFIX = "/api/";
|
||||
|
||||
export default {
|
||||
async fetch(request) {
|
||||
if (request.method === "OPTIONS") {
|
||||
return cors(new Response(null, { status: 204 }));
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (url.pathname === "/" || url.pathname === "/health") {
|
||||
return cors(
|
||||
new Response(JSON.stringify({ ok: true, service: "cryptocoin-binance-proxy" }), {
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (!url.pathname.startsWith(ALLOWED_PREFIX)) {
|
||||
return cors(new Response("Not Found", { status: 404 }));
|
||||
}
|
||||
|
||||
const target = `${BINANCE_ORIGIN}${url.pathname}${url.search}`;
|
||||
|
||||
try {
|
||||
const upstream = await fetch(target, {
|
||||
method: request.method,
|
||||
headers: {
|
||||
"User-Agent": "CryptoCoin-Widget/1.0",
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
const body = await upstream.arrayBuffer();
|
||||
const headers = new Headers(upstream.headers);
|
||||
headers.set("access-control-allow-origin", "*");
|
||||
|
||||
return new Response(body, {
|
||||
status: upstream.status,
|
||||
statusText: upstream.statusText,
|
||||
headers,
|
||||
});
|
||||
} catch (err) {
|
||||
return cors(
|
||||
new Response(JSON.stringify({ error: String(err) }), {
|
||||
status: 502,
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
function cors(response) {
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("access-control-allow-origin", "*");
|
||||
headers.set("access-control-allow-methods", "GET, OPTIONS");
|
||||
headers.set("access-control-allow-headers", "Content-Type");
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user