simple-proxy.js 641 B

123456789101112131415161718192021222324252627
  1. 'use strict'
  2. const http = require('http')
  3. const https = require('https')
  4. const server = http.createServer(handler)
  5. const port = +process.argv[2]
  6. const prefix = process.argv[3]
  7. const upstream = process.argv[4]
  8. var calls = 0
  9. server.listen(port)
  10. function handler (req, res) {
  11. if (req.url.indexOf(prefix) !== 0) {
  12. throw new Error('request url [' + req.url + '] does not start with [' + prefix + ']')
  13. }
  14. var upstreamUrl = upstream + req.url.substring(prefix.length)
  15. https.get(upstreamUrl, function (ures) {
  16. ures.on('end', function () {
  17. if (++calls === 2) {
  18. server.close()
  19. }
  20. })
  21. ures.pipe(res)
  22. })
  23. }