Backblaze B2利用Cloudfare Workers建立对象存储

Backblaze B2 & Cloudflare
Backblaze B2 & Cloudflare

BackBlaze B2作为存储大厂的价格非常便宜,速度也非常快,加上与Cloudfare都在带宽联盟内,可以免去流量费用。

但是如果直接在Cloudfare上用于绑定BackBlaze桶,会有file+桶名的多余地址。

这里主要讲的是利用Cloudfare Workers实现完全BackBlaze B2桶的自定义访问地址(Workers免费计划有十万请求的限制,一般网站2500IP以上要考虑付费计划)

Wokers代码一:

'use strict';
const b2Domain = 'img.domain.com'; // configure this as per instructions above
const b2Bucket = 'bucket-name'; // configure this as per instructions above
const b2UrlPath = `/file/${b2Bucket}/`;
addEventListener('fetch', event => {
return event.respondWith(fileReq(event));
});

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

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

// define a function we can re-use to fix headers
const fixHeaders = function(url, status, headers){
let newHdrs = new Headers(headers);
// add basic cors headers for images
if(corsFileTypes.includes(url.pathname.split('.').pop())){
newHdrs.set('Access-Control-Allow-Origin', '*');
}
// override browser cache for files when 200
if(status === 200){
newHdrs.set('Cache-Control', "public, max-age=" + expiration);
}else{
// only cache other things for 5 minutes
newHdrs.set('Cache-Control', 'public, max-age=300');
}
// set ETag for efficient caching where possible
const ETag = newHdrs.get('x-bz-content-sha1') || newHdrs.get('x-bz-info-src_last_modified_millis') || newHdrs.get('x-bz-file-id');
if(ETag){
newHdrs.set('ETag', ETag);
}
// remove unnecessary headers
removeHeaders.forEach(header => {
newHdrs.delete(header);
});
return newHdrs;
};
async function fileReq(event){
const cache = caches.default; // Cloudflare edge caching
const url = new URL(event.request.url);
if(url.host === b2Domain && !url.pathname.startsWith(b2UrlPath)){
url.pathname = b2UrlPath + url.pathname;
}
let response = await cache.match(url); // try to find match for this request in the edge cache
if(response){
// use cache found on Cloudflare edge. Set X-Worker-Cache header for helpful debug
let newHdrs = fixHeaders(url, response.status, response.headers);
newHdrs.set('X-Worker-Cache', "true");
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHdrs
});
}
// no cache, fetch image, apply Cloudflare lossless compression
response = await fetch(url, {cf: {polish: "lossless"}});
let newHdrs = fixHeaders(url, response.status, response.headers);

if(response.status === 200){

response = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHdrs
});
}else{
response = new Response('File not found!', { status: 404 })
}

event.waitUntil(cache.put(url, response.clone()));
return response;
}

Workers代码二:

const baseUrl = "https://f000.backblazeb2.com/file/platformracing-com"

addEventListener('fetch', event => {
event.respondWith(handleRequest(event))
})

/**
* Return appropriate content type based on file name
* @param {string} name
*/
function nameToType(name) {
const arr = name.split('.')
const extention = arr[arr.length - 1]
const map = {
html: 'text/html',
js: 'application/javascript',
css: 'text/css',
woff2: 'binary/octet-stream'
}
return map[extention] || 'binary/octet-stream'
}

/**
* Serve content from B2
* @param {Request} request
*/
async function handleRequest(event) {
// only allow get requests
if (event.request.method !== 'GET') {
return new Response('Method not allowed', { status: 405 })
}

// return a chached response if we have one
const cache = caches.default
let cachedResponse = await cache.match(event.request)
if (cachedResponse) {
return cachedResponse
}

// look for default index.html
const url = new URL(event.request.url)
let pathname = url.pathname
if (pathname === '' || pathname === '/') {
pathname = '/index.html'
}

// add some headers
const headers = {
'cache-control': 'public, max-age=14400',
'content-type': nameToType(pathname)
}

// fetch content from B2
const b2Response = await fetch(`${baseUrl}${pathname}`)
const response = new Response(b2Response.body, { ...b2Response, headers })

// return minimal error page
if (response.status > 399) {
return new Response(response.statusText, { status: response.status })
}

// all is well, return the response
event.waitUntil(cache.put(event.request, response.clone()))
return response
}


发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注