浏览代码

修复 cfworker 不发送 POST 数据的问题 #106,增加 HTTP 跳转 HTTPS 的功能 #104

zjcqoo 6 年之前
父节点
当前提交
f3bce7dcac
共有 1 个文件被更改,包括 37 次插入19 次删除
  1. 37 19
      cf-worker/index.js

+ 37 - 19
cf-worker/index.js

@@ -5,7 +5,7 @@
  */
 const ASSET_URL = 'https://zjcqoo.github.io'
 
-const JS_VER = 7
+const JS_VER = 8
 const MAX_RETRY = 1
 
 
@@ -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()
@@ -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)
 }
 
@@ -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) {