在Web 开发中,获取用户的地理位置信息对许多应用场景非常重要,比如根据用户所在地调整内容、提高安全性、进行数据分析、国际化站点跳转等等。借助 Cloudflare Workers,开发者可以轻松创建一个高效的 API,来查询 IP 地址的地理位置信息,大家很容易就可以获得一个免费地理位置API,强烈推荐。
本文将详细介绍如何使用 Cloudflare Workers 构建一个查询 IP 地理位置信息的 API,并结合 Cloudflare 提供的免费 GeoIP 数据,快速实现此功能。
文章目录
Cloudflare Workers 是一个无服务器(Serverless)平台,允许开发者在 Cloudflare 的全球网络上运行 JavaScript、WASM 等代码。相比传统的后端架构,它具有以下优势:
要创建一个 Cloudflare Worker,首先需要一个 Cloudflare 账户。以下是设置步骤:
Cloudflare 在每个 HTTP 请求中自动附带 GeoIP 数据,因此我们可以轻松访问用户的地理位置信息,而无需外部 API。这些数据包括:
request.cf.country
)request.cf.timezone
)request.cf.region
)request.cf.city
)request.cf.latitude
与 request.cf.longitude
)以下是我的 Cloudflare Worker的配置,它接收一个 IP 请求并返回该 IP 的地理位置信息:
export default {
async fetch(request, env, ctx) {
const data = {
Method: request.method,
Url: request.url,
IP: {
IP: request.headers.get('CF-Connecting-IP'),
Continent: request.cf.continent,
Country: request.cf.country,
IsEU: request.cf.isEUCountry,
Region: request.cf.region,
RegionCode: request.cf.regionCode,
City: request.cf.city,
Latitude: request.cf.latitude,
Longitude: request.cf.longitude,
PostalCode: request.cf.postalCode,
MetroCode: request.cf.metroCode,
Colo: request.cf.colo,
ASN: request.cf.asn,
ASOrganization: request.cf.asOrganization,
Timezone: request.cf.timezone
},
Headers: {},
Security: {}
};
// 遍历并存储每个 HTTP 头,排除以 cf- 开头的 HTTP 头
request.headers.forEach((value, name) => {
if (!name.toLowerCase().startsWith('cf-')) {
data.Headers[name] = value;
}
});
// 遍历 request.cf 并存储所需对象的属性到 Security 中
for (const key in request.cf) {
if (
key == 'clientTcpRtt'
|| key == 'tlsCipher'
|| key == 'tlsVersion'
|| key == 'httpProtocol'
|| key == 'clientHandshake'
|| key == 'clientFinished'
|| key == 'serverHandshake'
|| key == 'serverFinished'
|| key == 'corporateProxy'
|| key == 'verifiedBot'
|| key == 'score'
) {
if (typeof request.cf[key] === 'object') {
for (const innerKey in request.cf[key]) {
data.Security[innerKey] = request.cf[key][innerKey];
}
} else {
data.Security[key] = request.cf[key];
}
}
}
var dataJson = JSON.stringify(data, null, 4);
//console.log(dataJson);
return new Response(dataJson, {
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "https://www."
}
})
},
};
编写完代码后,可以将 Worker 部署到 Cloudflare 边缘网络上:
https://your-worker-url.workers.dev/
。curl
或者浏览器直接请求你的 API,验证它是否能正确返回 IP 地址的地理位置信息。curl https://your-worker-url.workers.dev/
API 将返回类似如下的响应:
有时,你可能想查询指定 IP 地址的地理信息,而不仅仅是查询请求发起者的 IP 地址。Cloudflare Workers 支持通过自定义逻辑来处理这种需求。
可以修改代码,使其接受查询参数,从而处理特定 IP 的地理位置信息。例如:
async function handleRequest(request) {
const url = new URL(request.url)
const ip = url.searchParams.get('ip')
// 如果没有提供 IP,则使用请求的源 IP
const cf = ip ? { country: 'XX', city: 'Example' } : request.cf
if (cf) {
const geoInfo = {
country: cf.country || 'Unknown',
region: cf.region || 'Unknown',
city: cf.city || 'Unknown',
latitude: cf.latitude || 'Unknown',
longitude: cf.longitude || 'Unknown',
timezone: cf.timezone || 'Unknown'
}
return new Response(JSON.stringify(geoInfo), {
headers: { 'Content-Type': 'application/json' }
})
} else {
return new Response('Unable to retrieve IP geo information', { status: 400 })
}
}
由于 IP 信息是敏感数据,为了防止滥用,可以在 API 上加上速率限制(Rate Limiting),并使用 Cloudflare 提供的安全功能,如 WAF(Web Application Firewall)来过滤恶意请求。
最后注意cloudflare的worker每天的调用次数是有限的10万次,一般的网站够用了,具体看这里。
通过 Cloudflare Workers,我们可以轻松构建一个查询 IP 地理位置信息的 API,利用 Cloudflare 内置的 GeoIP 数据,不需要额外依赖外部服务。同时,借助 Cloudflare 全球边缘网络,API 的性能非常高,并且具备极好的弹性和安全性。
这种 API 可以用于多种场景,比如动态内容本地化、安全性增强以及用户分析等。在构建过程中,我们只需要编写少量代码,并且 Cloudflare 提供了简洁的开发体验,让开发者可以快速上线自己的服务。