Skip to content

Instantly share code, notes, and snippets.

@ecyshor
Last active March 8, 2023 04:36
Show Gist options
  • Save ecyshor/0138ea1f8b0b16b1b7357a936d060b66 to your computer and use it in GitHub Desktop.
Save ecyshor/0138ea1f8b0b16b1b7357a936d060b66 to your computer and use it in GitHub Desktop.
nodejs reverse proxy google cloud function
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 = {
// 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();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment