全球主机交流论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

CeraNetworks网络延迟测速工具IP归属甄别会员请立即修改密码
查看: 1597|回复: 3

[翻译] Workers如何实现类似Nginx location的功能?

[复制链接]
发表于 2021-7-10 19:18:32 | 显示全部楼层 |阅读模式
本帖最后由 MoeWang 于 2021-7-10 23:14 编辑

如题,是这样的,我把原来vercel的b2对象存储反代移到workers来了(看中了带宽联盟),然后我就找了找论坛里的workers反代隐藏path,然后就卡在这里了。。原因是我在vercel里面设置过不同的路由,比如/avatar/的path是用来反代gravatar的,传入的path符合条件的话(比如https://workers/avatar/xxxxxx)就执行反代gravatar的代码;

如果传入的URL不包含avatar(比如https://workers/test.jpg或者https://workers/public/123.js)就继续反代对象存储。

让我写个nginx或者vercel的那种path路由我会,但是换用service workers就真的不会了,

主要是如何监听不同路径这块代码不是很熟悉。如果要想复杂些的话这种要用if吗?

然后可能真的没找对关键词,网上我就没搜着service workers 分path执行的相关教程,所以来问问各位大佬。能给我一篇讲如何监听不同目录的文档或者教程也行。。吐了。。。救救孩子吧

目前搜到的代码如下:

  1. //gravatar反代
  2. addEventListener(
  3.   "fetch",event => {
  4.     let url=new URL(event.request.url);
  5.     url.hostname="secure.gravatar.com";
  6.     url.pathname="/avatar/";
  7.     let request=new Request(url,event.request);
  8.      event. respondWith(
  9.        fetch(request)
  10.        )
  11.        }
  12.         )

  13. //gravatar反代 结束
  14. //B2 存储隐藏桶 开始
  15. 'use strict';
  16. const b2Domain = 'cdn.xxxxx'; // configure this as per instructions above
  17. const b2Bucket = 'xxxxxxx; // configure this as per instructions above
  18. const b2UrlPath = `/file/${b2Bucket}/`;
  19. addEventListener('fetch', event => {
  20.         return event.respondWith(fileReq(event));
  21. });

  22. // define the file extensions we wish to add basic access control headers to
  23. const corsFileTypes = ['png', 'jpg', 'gif', 'jpeg', 'webp'];

  24. // backblaze returns some additional headers that are useful for debugging, but unnecessary in production. We can remove these to save some size
  25. const removeHeaders = [
  26.         'x-bz-content-sha1',
  27.         'x-bz-file-id',
  28.         'x-bz-file-name',
  29.         'x-bz-info-src_last_modified_millis',
  30.         'X-Bz-Upload-Timestamp',
  31.         'Expires'
  32. ];
  33. const expiration = 31536000; // override browser cache for images - 1 year

  34. // define a function we can re-use to fix headers
  35. const fixHeaders = function(url, status, headers){
  36.         let newHdrs = new Headers(headers);
  37.         // add basic cors headers for images
  38.         if(corsFileTypes.includes(url.pathname.split('.').pop())){
  39.                 newHdrs.set('Access-Control-Allow-Origin', '*');
  40.         }
  41.         // override browser cache for files when 200
  42.         if(status === 200){
  43.                 newHdrs.set('Cache-Control', "public, max-age=" + expiration);
  44.         }else{
  45.                 // only cache other things for 5 minutes
  46.                 newHdrs.set('Cache-Control', 'public, max-age=300');
  47.         }
  48.         // set ETag for efficient caching where possible
  49.         const ETag = newHdrs.get('x-bz-content-sha1') || newHdrs.get('x-bz-info-src_last_modified_millis') || newHdrs.get('x-bz-file-id');
  50.         if(ETag){
  51.                 newHdrs.set('ETag', ETag);
  52.         }
  53.         // remove unnecessary headers
  54.         removeHeaders.forEach(header => {
  55.                 newHdrs.delete(header);
  56.         });
  57.         return newHdrs;
  58. };
  59. async function fileReq(event){
  60.         const cache = caches.default; // Cloudflare edge caching
  61.         const url = new URL(event.request.url);
  62.         if(url.host === b2Domain && !url.pathname.startsWith(b2UrlPath)){
  63.                 url.pathname = b2UrlPath + url.pathname;
  64.         }
  65.         let response = await cache.match(url); // try to find match for this request in the edge cache
  66.         if(response){
  67.                 // use cache found on Cloudflare edge. Set X-Worker-Cache header for helpful debug
  68.                 let newHdrs = fixHeaders(url, response.status, response.headers);
  69.                 newHdrs.set('X-Worker-Cache', "true");
  70.                 return new Response(response.body, {
  71.                         status: response.status,
  72.                         statusText: response.statusText,
  73.                         headers: newHdrs
  74.                 });
  75.         }
  76.         // no cache, fetch image, apply Cloudflare lossless compression
  77.         response = await fetch(url, {cf: {polish: "lossless"}});
  78.         let newHdrs = fixHeaders(url, response.status, response.headers);

  79.   if(response.status === 200){

  80.     response = new Response(response.body, {
  81.       status: response.status,
  82.       statusText: response.statusText,
  83.       headers: newHdrs
  84.     });
  85.   }else{
  86.     response = new Response('Not Found!', { status: 404 })
  87.   }

  88.         event.waitUntil(cache.put(url, response.clone()));
  89.         return response;
  90. }
  91. //B2 存储桶 结束
复制代码

另外本帖不会255,我也没有255的习惯
发表于 2021-7-10 19:22:34 | 显示全部楼层
https://github.com/kwhitley/itty-router
https://github.com/cfworker/cfworker/tree/main/packages/web
https://github.com/berstend/tiny-request-router
 楼主| 发表于 2021-7-10 19:25:56 | 显示全部楼层
滴滴单车 发表于 2021-7-10 19:22
https://github.com/kwhitley/itty-router
https://github.com/cfworker/cfworker/tree/main/packages/web
...

感谢大佬,有头绪了,待会试试
byg 该用户已被删除
发表于 2021-7-10 21:32:07 | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|全球主机交流论坛

GMT+8, 2024-11-26 08:41 , Processed in 0.068893 second(s), 10 queries , Gzip On, MemCache On.

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表