1243 条记录
52 私有链接
52 私有链接
// API 密钥和主机
const API_HOST = 'generativelanguage.googleapis.com';
const api_secret = "自定义apikey";
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
// 处理 OPTIONS 请求
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Headers': 'Content-Type, Accept, x-goog-api-key',
'Access-Control-Max-Age': '86400' // 缓存 OPTIONS 响应 1 天
},
status: 204
});
}
const url = new URL(request.url);
const path = url.pathname;
const keyParam = url.searchParams.get('key');
const apiKeyHeader = request.headers.get('x-goog-api-key');
let key = '';
if(keyParam) {
key = keyParam
} else if (apiKeyHeader) {
key = apiKeyHeader
}
console.log(key)
// API 密钥验证
if (key === '' || key !== api_secret) {
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
status: 401,
headers: { 'Content-Type': 'application/json' }
});
}
// 获取 API 密钥数组
const API_KEYS = JSON.parse(await api_keys.get('API_KEYS') || '[]'); // 确保处理 API_KEYS 缺失的情况
// 如果没有配置 API Key数组, 直接使用 api_secret
let API_KEY = api_secret;
if (API_KEYS.length > 0) {
API_KEY = selectApiKey(API_KEYS);
}
// 记录使用的 API 密钥
console.log(`Using API KEY: ${API_KEY}`);
const newHeaders = new Headers(request.headers);
// 修改请求
url.hostname = API_HOST;
if (path.includes(":generateContent")) {
url.searchParams.set('key', API_KEY);
newHeaders.set('x-goog-api-key', API_KEY); // 设置新的请求头
}
if (path.includes(":streamGenerateContent")) {
newHeaders.set('x-goog-api-key', API_KEY); // 设置新的请求头
url.searchParams.set('key', API_KEY);
}
if (path.includes("models")) {
url.searchParams.set("key", API_KEY);
}
const modifiedRequest = new Request(url.toString(), {
method: request.method,
headers: newHeaders,
body: request.body,
redirect: 'follow'
});
try {
const response = await fetch(modifiedRequest);
return new Response(response.body, response);
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
function selectApiKey(apiKeys) {
// 随机选择一个 API 密钥
const randomIndex = Math.floor(Math.random() * apiKeys.length);
return apiKeys[randomIndex];
}