From 1a894968fcf0f664210e3b2c1d0ebe0c5b5725a0 Mon Sep 17 00:00:00 2001 From: Phillweston <2436559745@qq.com> Date: Sun, 31 Mar 2024 10:54:31 +0800 Subject: [PATCH] Add Cloudflare worker automation scripts --- .github/workflows/worker.yml | 23 +++++++++++++++++++++++ worker/worker.js | 27 +++++++++++++++++++++++++++ wrangle.toml | 8 ++++++++ 3 files changed, 58 insertions(+) create mode 100644 .github/workflows/worker.yml create mode 100644 worker/worker.js create mode 100644 wrangle.toml diff --git a/.github/workflows/worker.yml b/.github/workflows/worker.yml new file mode 100644 index 0000000..6b06bd2 --- /dev/null +++ b/.github/workflows/worker.yml @@ -0,0 +1,23 @@ +name: Deploy Worker to Cloudflare + +on: + push: + branches: ["master"] + +jobs: + deploy: + runs-on: ubuntu-latest + defaults: + run: + working-directory: worker + steps: + - uses: actions/checkout@v2 + + - name: Install Wrangler + run: npm install -g wrangler + + - name: Publish the Worker + run: wrangler publish --env production + env: + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + CLOUDFLARE_API_KEY: ${{ secrets.CLOUDFLARE_API_KEY }} diff --git a/worker/worker.js b/worker/worker.js new file mode 100644 index 0000000..e33f0e2 --- /dev/null +++ b/worker/worker.js @@ -0,0 +1,27 @@ +addEventListener('fetch', event => { + event.respondWith(handleRequest(event.request)); +}); + +async function handleRequest(request) { + // Modify the request URL + const url = new URL(request.url); + url.protocol = 'http:'; + url.hostname = 'host.btiplatform.com'; + url.port = '8080'; + + // Fetch the data from the modified URL + const response = await fetch(url.toString(), request); + + // Create a new response with CORS headers + const newHeaders = new Headers(response.headers); + newHeaders.set("Access-Control-Allow-Origin", "*"); // Adjust as needed for security + newHeaders.set("Access-Control-Allow-Methods", "GET, POST"); + newHeaders.set("Access-Control-Allow-Headers", "Content-Type, Authorization"); + + // Return the response with the new headers + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers: newHeaders + }); +} \ No newline at end of file diff --git a/wrangle.toml b/wrangle.toml new file mode 100644 index 0000000..40ec92c --- /dev/null +++ b/wrangle.toml @@ -0,0 +1,8 @@ +name = "api" + +[site] +bucket = "./worker" # Path to your worker code + +[env.production] +# The account_id is set through an environment variable in the GitHub Actions workflow +account_id = "$CLOUDFLARE_ACCOUNT_ID" \ No newline at end of file