Skip to content

Commit

Permalink
修复 cfworker 不发送 POST 数据的问题 EtherDream#106,增加 HTTP 跳转 HTTPS 的功能 EtherD…
Browse files Browse the repository at this point in the history
  • Loading branch information
EtherDream committed Jul 11, 2019
2 parents 475d1b9 + 91e46d7 commit f3bce7d
Showing 1 changed file with 37 additions and 19 deletions.
56 changes: 37 additions & 19 deletions cf-worker/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/
const ASSET_URL = 'https://zjcqoo.github.io'

const JS_VER = 7
const JS_VER = 8
const MAX_RETRY = 1


Expand All @@ -22,44 +22,55 @@ const PREFLIGHT_INIT = {
/**
* @param {string} message
* @param {number} status
* @param {any} headers
*/
function makeRes(message, status) {
return new Response(message, {
status,
headers: {
'cache-control': 'no-cache'
}
})
function makeRes(message, status = 200, headers = {}) {
headers['cache-control'] = 'no-cache'
headers['vary'] = '--url'
headers['access-control-allow-origin'] = '*'
return new Response(message, {status, headers})
}


addEventListener('fetch', e => {
const ret = fetchHandler(e)
.catch(err => makeRes('cfworker error:' + err, 502))
e.respondWith(ret)
})


function fetchHandler(e) {
const req = e.request
const urlStr = req.url
const urlObj = new URL(urlStr)
let ret

if (urlObj.protocol === 'http:') {
urlObj.protocol = 'https:'
return makeRes('', 301, {
'strict-transport-security': 'max-age=99999999; includeSubDomains; preload',
'location': urlObj.href,
})
}

switch (urlObj.pathname) {
case '/http':
ret = handler(req)
break
return httpHandler(req)
case '/ws':
return makeRes('not support', 400)
case '/works':
ret = makeRes('it works', 200)
break
return makeRes('it works')
default:
// static files
ret = fetch(ASSET_URL + urlObj.pathname)
break
return fetch(ASSET_URL + urlObj.pathname)
}
e.respondWith(ret)
})
}



/**
* @param {Request} req
*/
async function handler(req) {
async function httpHandler(req) {
const reqHdrRaw = req.headers
if (reqHdrRaw.has('x-jsproxy')) {
return Response.error()
Expand Down Expand Up @@ -123,10 +134,15 @@ async function handler(req) {
if (!urlObj) {
return makeRes('missing url param', 403)
}

/** @type {RequestInit} */
const reqInit = {
method: req.method,
headers: reqHdrNew,
}
if (req.method === 'POST') {
reqInit.body = req.body
}
return proxy(urlObj, reqInit, acehOld, rawLen, 0)
}

Expand Down Expand Up @@ -190,7 +206,9 @@ async function proxy(urlObj, reqInit, acehOld, rawLen, retryTimes) {
return proxy(urlObj, reqInit, acehOld, rawLen, retryTimes + 1)
}
}
return makeRes(`bad len (old: ${rawLen} new: ${newLen})`, 400)
return makeRes('error', 400, {
'--error': 'bad len:' + newLen
})
}

if (retryTimes > 1) {
Expand Down

0 comments on commit f3bce7d

Please sign in to comment.