利用CloudFlare-Worker加速你的GitPage

Cloudflare 提供每天 10 万次的免费请求额度

如何部署Cloudflare Worker?

  • 首页:https://workers.cloudflare.com
  • 注册,登陆,Start building,取一个子域名,Create a Worker
  • 复制下面代码到左侧代码框,Save and deploy。如果正常,右侧应显示首页。
  • 收藏地址框中的 https://xxxx.子域名.workers.dev,以后可直接访问
// 定义 Github  信息
const github_Name = 'Your-Github-UserName'; //Github 用户名
const github_Repo = 'Your-Github-RepoName'; //Github 仓库名
const github_base = `${github_Name}/${github_Repo}`;

/* 配置到此结束 */


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

async function bloghandle(request) {
    const urlObj = new URL(request.url);
    const path = urlObj.href.substr(urlObj.origin.length);
    const init = {
        method: "GET"
    };
    var data = '';
    if (path) {
        var url = "https://raw.githubusercontent.com/" + github_base + "/master" + path + '/index.html';
        const response = await fetch(url, init);
        var resptxt = await response.text();
        data += resptxt;
    } else {
        var url = "https://raw.githubusercontent.com/" + github_base + '/master/index.html';
        const response = await fetch(url, init);
        if (response.status == 200) {
            var resptxt = await response.text();
            data += resptxt.replace(/`/g, "\\`");
        } else {
            var url = "https://raw.githubusercontent.com/" + github_base + '/master/404.html';
            const response = await fetch(url, init);
            if (response.status == 200) {
                var resptxt = await response.text();
                data += resptxt.replace(/`/g, "\\`");
            } else {
                data += `404 Page Not Found!`;
            }
        }
    }
    return data;
}

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
    var resp = new Response(await bloghandle(request), { "Content-type": "text/html;charset=UTF-8", status: 200 });
    resp.headers.set("Content-Type", "text/html");
    return resp;
}

添加新评论

评论列表