VPS/云主机等
优惠信息分享

搭建基于cloudflareworkers的GitHub文件加速

今天这篇文章,分享一下利用cloudflare workers自建一个API,来实现GitHub文件加速。之前分享过国内 GitHub 下载加速技巧分享,分享了2篇文章,如下:

[mark_b]

GitHub 下载速度慢?国内 GitHub 下载加速技巧分享

Github Action离线下载项目至坚果云WebDAV网盘

[/mark_b]

1、简介

github release、archive以及项目文件的加速项目,支持clone,有Cloudflare Workers无服务器版本以及Python版本

项目:https://github.com/hunshcn/gh-proxy

演示:https://cf.fdao.xyz/

2、准备

1)自备一个cloudflare账号(如何申请略过)

2)最好准备好一个域名,二级、三级域名都可以。

3、部署

1)新建worker

2)在脚本框中粘贴代码

代码:https://github.com/hunshcn/gh-proxy/blob/master/index.js

[reply]

'use strict'/** * static files (404.html, sw.js, conf.js) */const ASSET_URL = 'https://hunshcn.github.io/gh-proxy'// 前缀,如果自定义路由为example.com/gh/*,将PREFIX改为 '/gh/',注意,少一个杠都会错!const PREFIX = '/'// git使用cnpmjs镜像、分支文件使用jsDelivr镜像的开关,0为关闭,默认开启const Config = {    jsdelivr: 1,    cnpmjs: 1}/** @type {RequestInit} */const PREFLIGHT_INIT = {    status: 204,    headers: new Headers({        'access-control-allow-origin': '*',        'access-control-allow-methods': 'GET,POST,PUT,PATCH,TRACE,DELETE,HEAD,OPTIONS',        'access-control-max-age': '1728000',    }),}/** * @param {any} body * @param {number} status * @param {Object<string, string>} headers */function makeRes(body, status = 200, headers = {}) {    headers['access-control-allow-origin'] = '*'    return new Response(body, {status, headers})}/** * @param {string} urlStr */function newUrl(urlStr) {    try {        return new URL(urlStr)    } catch (err) {        return null    }}addEventListener('fetch', e => {    const ret = fetchHandler(e)        .catch(err => makeRes('cfworker error:\n' + err.stack, 502))    e.respondWith(ret)})/** * @param {FetchEvent} e */async function fetchHandler(e) {    const req = e.request    const urlStr = req.url    const urlObj = new URL(urlStr)    let path = urlObj.searchParams.get('q')    if (path) {        return Response.redirect('https://' + urlObj.host + PREFIX + path, 301)    }    // cfworker 会把路径中的 `//` 合并成 `/`    path = urlObj.href.substr(urlObj.origin.length + PREFIX.length).replace(/^https?:\/+/, 'https://')    const exp1 = /^(?:https?:\/\/)?github\.com\/.+?\/.+?\/(?:releases|archive)\/.*$/i    const exp2 = /^(?:https?:\/\/)?github\.com\/.+?\/.+?\/(?:blob)\/.*$/i    const exp3 = /^(?:https?:\/\/)?github\.com\/.+?\/.+?\/(?:info|git-).*$/i    const exp4 = /^(?:https?:\/\/)?raw\.githubusercontent\.com\/.+?\/.+?\/.+?\/.+$/i    if (path.search(exp1) === 0 || !Config.cnpmjs && (path.search(exp3) === 0 || path.search(exp4) === 0)) {        return httpHandler(req, path)    } else if (path.search(exp2) === 0) {        if (Config.jsdelivr){const newUrl = path.replace('/blob/', '@').replace(/^(?:https?:\/\/)?github\.com/, 'https://cdn.jsdelivr.net/gh')return Response.redirect(newUrl, 302)        }else{path = path.replace('/blob/', '/raw/')return httpHandler(req, path)        }    } else if (path.search(exp3) === 0) {        const newUrl = path.replace(/^(?:https?:\/\/)?github\.com/, 'https://github.com.cnpmjs.org')        return Response.redirect(newUrl, 302)    } else if (path.search(exp4) === 0) {        const newUrl = path.replace(/(?<=com\/.+?\/.+?)\/(.+?\/)/, '@$1').replace(/^(?:https?:\/\/)?raw\.githubusercontent\.com/, 'https://cdn.jsdelivr.net/gh')        return Response.redirect(newUrl, 302)    } else {        return fetch(ASSET_URL + path)    }}/** * @param {Request} req * @param {string} pathname */function httpHandler(req, pathname) {    const reqHdrRaw = req.headers    // preflight    if (req.method === 'OPTIONS' &&        reqHdrRaw.has('access-control-request-headers')    ) {        return new Response(null, PREFLIGHT_INIT)    }    let rawLen = ''    const reqHdrNew = new Headers(reqHdrRaw)    let urlStr = pathname    if (urlStr.startsWith('github')) {        urlStr = 'https://' + urlStr    }    const urlObj = newUrl(urlStr)    /** @type {RequestInit} */    const reqInit = {        method: req.method,        headers: reqHdrNew,        redirect: 'follow',        body: req.body    }    return proxy(urlObj, reqInit, rawLen, 0)}/** * * @param {URL} urlObj * @param {RequestInit} reqInit */async function proxy(urlObj, reqInit, rawLen) {    const res = await fetch(urlObj.href, reqInit)    const resHdrOld = res.headers    const resHdrNew = new Headers(resHdrOld)    // verify    if (rawLen) {        const newLen = resHdrOld.get('content-length') || ''        const badLen = (rawLen !== newLen)        if (badLen) {return makeRes(res.body, 400, {    '--error': `bad len: ${newLen}, except: ${rawLen}`,    'access-control-expose-headers': '--error',})        }    }    const status = res.status    resHdrNew.set('access-control-expose-headers', '*')    resHdrNew.set('access-control-allow-origin', '*')    resHdrNew.delete('content-security-policy')    resHdrNew.delete('content-security-policy-report-only')    resHdrNew.delete('clear-site-data')    return new Response(res.body, {        status,        headers: resHdrNew,    })}

[/reply]

3)保存并部署

上面的代码粘贴后,点击保存并部署即可。红框的地方可以点击预览。

4、添加路由(设置一个域名访问)

1)选择你事先准备好的域名,并进入管理,之后点击workers。

2)添加路由

3)添加要给解析(设置占位)

在DNS管理处,添加一个A解析,地址:8.8.8.8

5、演示以及使用方法

1)效果

2)使用

GitHub文件链接带不带协议头都可以,支持release、archive以及文件,右键复制出来的链接都是符合标准的。

release、archive使用cf加速,文件会跳转至JsDelivr

注意,不支持项目文件夹

符合规范的使用如下:

分支源码:https://github.com/hunshcn/project/archive/master.zip

release源码:https://github.com/hunshcn/project/archive/v0.1.0.tar.gz

release文件:https://github.com/hunshcn/project/releases/download/v0.1.0/example.zip

分支文件:https://github.com/hunshcn/project/blob/master/filename

6、最后

如果平时偶尔用用,可以使用别人搭建好的,如果用的很多,那么自建比较稳。

Cloudflare Workers免费套餐的每天10万请求数,足够你折腾了。

赞(0)
未经允许不得转载:遗弃你|YIQINI.COM » 搭建基于cloudflareworkers的GitHub文件加速

评论 抢沙发

评论前必须登录!

 

登录

找回密码

注册