前言
作为一名程序猿,访问github是避免不了的事情,但是在国内访问极其不稳定,时不时就网页无法打开,还得开启科学上网折腾,极度影响效率。今天主要和大家分享下2种方案,一种是加速github文件访问,一种是直接加速github访问。
前提条件
- 拥有一个域名并且托管CloudFlare
- 本地具备hosts动态更新条件(路由器级别,本文采用adguard home)
github文件加速
1、CloudFlare创建worker来加速文件访问,每天10万次访问完全足够,主要使用大佬项目:gh-proxy,直接新建workers,wocker.js代码如下,点击部署然后返回。
'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 = '/'
// 分支文件使用jsDelivr镜像的开关,0为关闭,默认关闭
const Config = {
jsdelivr: 0
}
const whiteList = [] // 白名单,路径里面有包含字符的才会通过,e.g. ['/username/']
/** @type {ResponseInit} */
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',
}),
}
const exp1 = /^(?:https?:\/\/)?github\.com\/.+?\/.+?\/(?:releases|archive)\/.*$/i
const exp2 = /^(?:https?:\/\/)?github\.com\/.+?\/.+?\/(?:blob|raw)\/.*$/i
const exp3 = /^(?:https?:\/\/)?github\.com\/.+?\/.+?\/(?:info|git-).*$/i
const exp4 = /^(?:https?:\/\/)?raw\.(?:githubusercontent|github)\.com\/.+?\/.+?\/.+?\/.+$/i
const exp5 = /^(?:https?:\/\/)?gist\.(?:githubusercontent|github)\.com\/.+?\/.+?\/.+$/i
const exp6 = /^(?:https?:\/\/)?github\.com\/.+?\/.+?\/tags.*$/i
/**
* @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)
})
function checkUrl(u) {
for (let i of [exp1, exp2, exp3, exp4, exp5, exp6]) {
if (u.search(i) === 0) {
return true
}
}
return false
}
/**
* @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://')
if (path.search(exp1) === 0 || path.search(exp5) === 0 || path.search(exp6) === 0 || 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(exp4) === 0) {
const newUrl = path.replace(/(?<=com\/.+?\/.+?)\/(.+?\/)/, '@$1').replace(/^(?:https?:\/\/)?raw\.(?:githubusercontent|github)\.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)
}
const reqHdrNew = new Headers(reqHdrRaw)
let urlStr = pathname
let flag = !Boolean(whiteList.length)
for (let i of whiteList) {
if (urlStr.includes(i)) {
flag = true
break
}
}
if (!flag) {
return new Response("blocked", {status: 403})
}
if (urlStr.search(/^https?:\/\//) !== 0) {
urlStr = 'https://' + urlStr
}
const urlObj = newUrl(urlStr)
/** @type {RequestInit} */
const reqInit = {
method: req.method,
headers: reqHdrNew,
redirect: 'manual',
body: req.body
}
return proxy(urlObj, reqInit)
}
/**
*
* @param {URL} urlObj
* @param {RequestInit} reqInit
*/
async function proxy(urlObj, reqInit) {
const res = await fetch(urlObj.href, reqInit)
const resHdrOld = res.headers
const resHdrNew = new Headers(resHdrOld)
const status = res.status
if (resHdrNew.has('location')) {
let _location = resHdrNew.get('location')
if (checkUrl(_location))
resHdrNew.set('location', PREFIX + _location)
else {
reqInit.redirect = 'follow'
return proxy(newUrl(_location), reqInit)
}
}
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,
})
}
2、设置>触发器,新增自定义域和路由即可,等待生效完成后,直接访问域名即可打开页面。后续github文件访问只需要在url链接前面加上你的域名地址即可。
hosts加速github访问
公共优选hosts加速
- GitHub520项目,直接使用hosts文件连接即可:https://raw.githubusercontent.com/521xueweihan/GitHub520/main/hosts,此处一般配合github文件加速方法食用。
- ineo6项目,hosts文件连接:https://raw.githubusercontent.com/ineo6/hosts/master/hosts
本地优选hosts加速
1、还是采用ineo6大佬的项目,下载对应的客户端,本文是放在青龙面板中运行,python脚本定时执行并刷新黑名单列表及时生效。
import asyncio
import subprocess
import time
import requests
from adguardhome import AdGuardHome
def generate_hosts():
port = "38888"
res = subprocess.getoutput("netstat -anp|grep " + port)
if "hosts-server" not in res:
command = "/public/tool/github/hosts-server --port=" + port
subprocess.Popen(command, shell=True)
time.sleep(3)
else:
print("hosts-server is start.")
print(res)
target_file = "/public/zdir/host/github.txt"
url = "http://localhost:" + port
retry_times = 0
while retry_times < 10:
try:
resp = requests.get(url)
if resp.status_code == 200 and resp.text:
with open(target_file, "wb") as f:
now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
f.write(("# Update at: " + now_time + "\n").encode("utf-8"))
f.write("# GitHub Host Start\n\n".encode("utf-8"))
f.write((resp.text + "\n").encode("utf-8"))
f.write("# GitHub Host End\n".encode("utf-8"))
print("文件:" + target_file + "写入成功")
break
except:
print("获取github信息失败")
time.sleep(5)
retry_times = retry_times + 1
async def refresh_adguard():
async with AdGuardHome(host="xxx.xxx.xxx.xxx", username="xxx", password='xxx', verify_ssl=False) as adguard:
await adguard.filtering.refresh(allowlist=False)
print("刷新adguard home白名单成功")
if __name__ == "__main__":
generate_hosts()
asyncio.run(refresh_adguard())
- port:hosts-server启动的端口,只会启动一次,可以自定义
- host:此处是指adgurad home对应的IP地址,端口默认3000
- username:登录账号
- password:登录密码
3、adguard home新增自定义黑名单,路径指向生成的文件即可
本地优选hosts优势
- 网络已有的优选hosts都是比较通用的,不一定符合各个地方的网络情况。
- 本地优选hosts可以更加频繁,及时选出可用的hosts,减少访问中断的可能
后记
通过本地优选github hosts后,访问稳定性和速度都有明显的提升,暂未出现不可访问的情况;后续可以定时监控下github网站访问情况,访问不通时可以立即触发一次优选,进一步提高可靠性。
评论区