Last active
January 29, 2020 12:02
-
-
Save Dobby233Liu/b23e1242558f340cea474a3380b1767a to your computer and use it in GitHub Desktop.
px2cfw but it's a special ncov api edition... demo: https://ncov-api-mirror.d2l.workers.dev/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event.request)) | |
}) | |
var BASE_URL = "https://lab.isaaclin.cn/nCoV"; | |
var HOST_URL = "https://github.com/Dobby233Liu"; | |
var HOST_NNM = "Dobby233Liu"; | |
var CREDITS_HTML | |
= ` | |
由<a href="${HOST_URL}">${HOST_NNM}</a>镜像。此镜像根目录直通原api目录,无需添加/nCoV在目录名前(虽然会自动处理)。原api:<a href="${BASE_URL}">${BASE_URL}</a>。<hr />` | |
var CREDITS_INSERT_AFTER_FIRST_ENTRY_OF = `body > div > p`; | |
RegExp.escape = function(str) | |
{ | |
var specials = /[.*+?|()\[\]{}\\$^]/g; // .*+?|()[]{}\$^ | |
return str.replace(specials, "\\$&"); | |
} | |
var oneOccurenceHandled = false; | |
class ElementHandler { | |
element(element) { | |
if (oneOccurenceHandled) return; | |
element.prepend(CREDITS_HTML, { html: true }); | |
oneOccurenceHandled = true; | |
} | |
} | |
/** | |
* Respond to the request | |
* @param {Request} request | |
*/ | |
async function handleRequest(request) { | |
oneOccurenceHandled = false; | |
var reqInit = { | |
method: request.method, | |
headers: request.headers, | |
redirect: "follow" | |
}; | |
var userPathName = new URL(request.url).pathname; | |
if (userPathName.toLowerCase().startsWith("/ncov")) userPathName = userPathName.replace(new RegExp(RegExp.escape("/ncov"), "i"), ""); | |
if (!(userPathName.startsWith("/"))) userPathName = "/" + userPathName; | |
console.info("goes to", userPathName); | |
var doInsertMyCredits = false; | |
if (userPathName == "/") doInsertMyCredits = true; | |
try { | |
if(request.method != "GET" && request.method != "HEAD") reqInit["body"] = request.body; | |
} catch {} | |
var returnValue; | |
var fetchEntry = await fetch(BASE_URL + userPathName + new URL(request.url).search); | |
returnValue = fetchEntry; | |
if (doInsertMyCredits) { | |
try { | |
returnValue = new HTMLRewriter().on(CREDITS_INSERT_AFTER_FIRST_ENTRY_OF, new ElementHandler()).transform(fetchEntry); | |
} catch (e) { | |
console.error("fuck", e); | |
} | |
} | |
return returnValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment