cloudflare
Serverless is the new black. I mean everybody I know is moving to the serverless platforms or launching one. OK, maybe not everyone but Cloudflare is definitely moving in this direction with an audacious relatively new project called Workers.dev (check out that coolest new domain extension .dev
Google just made available).
无服务器是新的黑手党。 我的意思是,我认识的每个人都在转向无服务器平台或启动一个平台。 是的,也许不是每个人都可以,但是Cloudflare肯定正在通过一个名为Workers.dev的相对大胆的相对较新的项目朝这个方向发展 (请查看Google刚刚提供了最酷的新域扩展.dev
)。
Today, let's explore what the heck is this new serverless platform about, how is it different than other serverless platforms (did someone say no cold starts!), and what do you say, let's write our first Cloudflare Worker.
今天,让我们探索这个新的无服务器平台到底有什么用,它与其他无服务器平台有何不同(有人说没有冷门开始!),您怎么说,让我们写我们的第一个Cloudflare Worker。
Let's understand Cloudflare Workers deeply. What's the big catch here?
让我们深入了解Cloudflare Workers。 这里有什么大收获?
Cloudflare Workers provides a serverless execution environment that allows you to create entirely new applications or augment existing ones without configuring or maintaining infrastructure. — Cloudflare Docs
Cloudflare Workers提供了一个无服务器执行环境,使您无需配置或维护基础结构即可创建全新的应用程序或扩充现有的应用程序。 — Cloudflare文件
all this sounds pretty awesome, tell me more! — Happy to oblige.
this 所有这些听起来都很棒,告诉我更多 ! —很乐意。
Serverless Computing with Cloudflare Workers. The Network is the Computer. Build serverless applications on Cloudflare's global cloud network of 165 data centers. — Cloudflare Workers
Cloudflare Workers的无服务器计算。 网络就是计算机。 在由165个数据中心组成的Cloudflare的全球云网络上构建无服务器应用程序。 — Cloudflare工人
yup, that's how I felt at first; tell me moaar!
y 是的,我一开始就是这样; 告诉我mo !
So, the Cloudflare Workers let you run JavaScript in hundreds of data centers around the world. Using a Worker, you can modify your site’s HTTP requests and responses, make parallel requests, or generate responses from the edge.
因此,Cloudflare Workers使您可以在全球数百个数据中心中运行JavaScript。 使用工作器,您可以修改站点的HTTP请求和响应,发出并行请求或从边缘生成响应。
Some more examples shared by CoudFlare are:
CoudFlare共享的更多示例是:
All of these actions happen inside Cloudflare’s network. Yes, your code will be deployed to hundreds of data centers around the world returning responses to your users faster than your origin ever could. You get all the speed and security of Cloudflare CDN with all the power of JavaScript.
所有这些动作都在Cloudflare的网络内部发生。 是的,您的代码将被部署到世界各地的数百个数据中心,以比您的来源更快的速度向用户返回响应。 借助JavaScript的所有功能,您将获得Cloudflare CDN的所有速度和安全性。
Let's create a couple of simple Cloudflare Workers to see what we can accomplish. Test out Workers free of charge on cloudflareworkers.com.
让我们创建几个简单的Cloudflare Workers,看看我们能完成什么。 在cloudflareworkers.com上免费测试工作者。
addEventListener('fetch', event => {
event.respondWith(new Response('Hello World; Learning Cloudflare Workers, eh?!'));
})
example here →
在此处测试此示例→
You can enable IP Geolocation to have Cloudflare geolocate visitors to your website and pass the country code to you in ISO 3166-1 Alpha 2 format. That sends the country code to a Cloudflare Worker in the form of a header called cf-ipcountry
— we can play around with it to block access on a specific service or API to a country.
您可以启用IP 地理定位,以使Cloudflare可以将访问者地理定位到您的网站,并以ISO 3166-1 Alpha 2格式将国家/地区代码传递给您。 这会将国家/地区代码以称为cf-ipcountry
的标头形式发送给Cloudflare工作者-我们可以使用它来阻止特定服务或API对某个国家/地区的访问。
/**
* CloudFlare Worker.
*
* Block access to given countries.
*/
addEventListener('fetch', event => {
event.respondWith(block(event.request));
});
// Add countries to this Set to block them.
const countries = new Set([
'US', // United States.
'SG', // Singapore.
'BR', // Brazil.
'PK', // Pakistan.
'NG' // Nigeria.
]);
/**
* Block requests.
*
* @param {*} request User's request.
*/
async function block(request) {
// Get country value from request headers.
const country = request.headers.get('cf-ipcountry');
// Find out if country is on the block list.
const isCountryBlocked = countries.has(country);
// If it's on the blocked list, give back a 403.
if (isCountryBlocked) {
return new Response(`SORRY: This page not available in your country!`, {
status: 403,
statusText: 'Forbidden'
});
}
// Catch-all return of the original response.
return await fetch(request);
}
example here →
在此处测试此示例→
I teach a course on VSCode Power User where I offer Purchasing Power Parity (PPP) discounts to developers from countries where the economy is not as strong as the US and many others. There's up to 60% discount available. While building PPP is a whole another debate, you can very easily see how Cloudflare Workers can help here.
我在VSCode Power User上开设了一门课程,向经济不如美国和其他许多国家强劲的国家的开发人员提供购买力平价(PPP)折扣。 有高达60%的折扣。 尽管构建PPP完全是另一场辩论,但您可以很容易地看到Cloudflare Workers如何在这里提供帮助。
Down here, I have built a simple model that checks user's country to respond back with a discount percentage — which ofcoruse can be used to configure a DOM element or another API as a whole.
在这里,我建立了一个简单的模型,该模型可以检查用户所在的国家/地区以打折百分比进行响应-ofcoruse可以用于整体配置DOM元素或其他API。
/**
* CloudFlare Worker.
*
* Purchasing Power Parity Discounts.
*/
addEventListener('fetch', event => {
event.respondWith(pppDiscount(event.request));
});
// Country with percentage of discount.
const discount = {
UK: 10,
CA: 20,
PK: 60,
NG: 60,
IN: 60,
BR: 60
};
/**
* Give Purchasing Power Parity Discounts.
*
* @param {*} request User's request.
*/
async function pppDiscount(request) {
// Get country value from request headers.
const country = request.headers.get('cf-ipcountry');
const yourDiscount = discount[country];
// If no discount.
if (yourDiscount === undefined) {
return new Response(`No Purchasing Power Parity Discount in your country.`);
} else {
// Return discount.
return new Response(`Purchasing Power Parity Discount in ${country}: ${yourDiscount} percent.`);
}
}
example here →
在此处测试此示例→
Go ahead and try out Cloudflare Workers. I for one am a big fan of workers and have just booked myself a subdomain via Workers.dev (tip: try double-clicking anywhere on the page and see what happens). You should also check out the documentation as well as the Cloudflare Worker Recipes.
继续尝试Cloudflare Workers。 我是一个非常喜欢工作的人,并且刚刚通过Workers.dev为自己预订了一个子域(提示:尝试双击页面上的任意位置,看看会发生什么)。 您还应该查看文档以及《 Cloudflare Worker食谱》 。
I hope you enjoyed the piece. Reach out (and say Hi) on Twitter if you'd like to chat about this. Peace! ✌️
我希望你喜欢这首乐曲。 如果您想聊天,请在Twitter上联系(并打个招呼)。 和平! ✌️
翻译自: https://scotch.io/tutorials/serverless-cloudflare-workers-are-pretty-awesome
cloudflare