addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
// 处理 GET 请求,返回 HTML 页面
if (request.method === 'GET' && url.pathname === '/') {
return new Response(htmlContent, {
headers: { 'Content-Type': 'text/html' }
})
}
// 处理汇率查询请求
if (request.method === 'GET' && url.pathname === '/exchange-rate') {
const fsym = url.searchParams.get('fsym')
const tsym = url.searchParams.get('tsym') || 'CNY'
try {
let rate
const resp = await fetch(https://api.exchangerate-api.com/v4/latest/${fsym})
const data = await resp.json()
if (data.rates[tsym]) {
rate = data.rates[tsym]
} else {
const resp2 = await fetch(https://womjj.deno.dev/rate?fsym=${fsym}&tsym=${tsym})
const obj = await resp2.json()
rate = obj[tsym] || obj['CNY']
}
return new Response(JSON.stringify({ rate }), {
headers: { 'Content-Type': 'application/json' }
})
} catch (error) {
return new Response(JSON.stringify({ error: '获取汇率失败' }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
})
}
}
return new Response('Not Found', { status: 404 })
}
// 嵌入 HTML 页面内容
const htmlContent = `