Skip to content

Instantly share code, notes, and snippets.

@ecyshor
Last active March 8, 2023 04:36
Show Gist options
  • Select an option

  • Save ecyshor/0138ea1f8b0b16b1b7357a936d060b66 to your computer and use it in GitHub Desktop.

Select an option

Save ecyshor/0138ea1f8b0b16b1b7357a936d060b66 to your computer and use it in GitHub Desktop.

Revisions

  1. ecyshor revised this gist Mar 18, 2021. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion proxy.ts
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,7 @@ import * as functions from 'firebase-functions';
    import * as http from 'http';

    const BUCKET_NAME = "target-bucket"

    // check original code idea https://stackoverflow.com/a/10435819
    exports.rewriteGCSRequest = functions.https.onRequest((oreq: any, ores: any) => {
    const redirectPath = oreq.originalUrl === '/' ? '/index.html' : oreq.originalUrl
    const options = {
  2. ecyshor created this gist Mar 18, 2021.
    58 changes: 58 additions & 0 deletions proxy.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    import * as functions from 'firebase-functions';

    import * as http from 'http';

    const BUCKET_NAME = "target-bucket"

    exports.rewriteGCSRequest = functions.https.onRequest((oreq: any, ores: any) => {
    const redirectPath = oreq.originalUrl === '/' ? '/index.html' : oreq.originalUrl
    const options = {
    // host to forward to
    host: 'storage.googleapis.com',
    // port to forward to
    port: 80,
    // path to forward to
    path: `${BUCKET_NAME}/${oreq.hostname}${redirectPath}`,
    // request method
    method: 'GET',
    // headers to send
    headers: oreq.headers,
    agent: httpAgent
    };

    const creq = http
    .request(options, pres => {

    // set http status code based on proxied response
    ores.writeHead(pres.statusCode, pres.headers);

    // wait for data
    pres.on('data', chunk => {
    ores.write(chunk);
    });

    pres.on('close', () => {
    // closed, let's end client request as well
    ores.end();
    });

    pres.on('end', () => {
    // finished, let's finish client request as well
    ores.end();
    });
    })
    .on('error', e => {
    // we got an error
    console.error(e);
    try {
    // attempt to set error message and http status
    ores.writeHead(500);
    ores.write(e.message);
    } catch (error) {
    // ignore
    }
    ores.end();
    });

    creq.end();
    })