使用CF Workers自建随机图API
使用CF Workers自建随机图API
部署流程
在CF创建一个JS的Worker模板,然后编辑代码
复制粘贴下面代码,修改开头的主机名列表为你自己的主机名,然后部署
// 设置允许的主机名列表(支持泛域名) const allowedHostPatterns = [ /.*\.123456\.xyz$/ // 匹配 *.123456.xyz ]; const imgIndexUrl = 'https://raw.githubusercontent.com/Zxis233/img2122w10p/refs/heads/master/img.txt'; async function fetchImageIndex() { const response = await fetch(imgIndexUrl); if (!response.ok) { throw new Error('Failed to fetch image index'); } const text = await response.text(); return text.split('\n').map(line => line.trim()).filter(line => line.length > 0); } async function handleRequest(request) { // 处理 CORS 预检请求 if (request.method === 'OPTIONS') { return new Response(null, { status: 204, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, OPTIONS', 'Access-Control-Allow-Headers': '*', 'Access-Control-Max-Age': '86400', }, }); } try { const hostname = new URL(request.url).hostname; const isAllowed = allowedHostPatterns.some(pattern => typeof pattern === 'string' ? hostname === pattern : pattern.test(hostname) ); if (!isAllowed) { return new Response('Forbidden', { status: 403 }); } const images = await fetchImageIndex(); const randomImage = images[Math.floor(Math.random() * images.length)]; const imageUrl = `https://raw.githubusercontent.com/Zxis233/img2122w10p/master/${randomImage}`; const imageResponse = await fetch(imageUrl); if (!imageResponse.ok) { throw new Error('Failed to fetch image'); } // 创建新的响应头,包含 CORS 头部 const headers = new Headers(imageResponse.headers); headers.set('Access-Control-Allow-Origin', '*'); headers.set('Access-Control-Allow-Methods', 'GET, OPTIONS'); headers.set('Access-Control-Max-Age', '86400'); return new Response(imageResponse.body, { status: 200, headers: headers, }); } catch (error) { return new Response('Error: ' + error.message, { status: 500, headers: { 'Access-Control-Allow-Origin': '*', } }); } } addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)); });
最后
本教程参考自Zxis233的博客,在搭建过程中发现由于仓库结构变化原代码无法使用,故略作修改,感谢原作者分享
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 洛风缘的小屋!