Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. var url = require( 'url' ),
  2. http = require( 'http' ),
  3. https = require( 'https' );
  4.  
  5. function Proxy( api, port ) {
  6. var that = this;
  7. this.api = api;
  8. this.port = port;
  9. this.server = api.createServer( function ( clientRequest, clientResponse ) {
  10. that.request = new Request( clientRequest, clientResponse );
  11. } );
  12. this.server.listen( this.port );
  13. }
  14.  
  15. function Request( clientRequest, clientResponse ) {
  16. this.clientRequest = clientRequest;
  17. this.clientResponse = clientResponse;
  18. this.$_GET = url.parse( clientRequest.url, true ).query;
  19. this.url = this.$_GET.url;
  20. if ( this.url ) {
  21. var clientRequestUrl = this.clientRequestUrl = url.parse( this.url );
  22. this.ssl = clientRequestUrl.protocol !== 'http:';
  23. this.api = this.ssl ? https : http;
  24. this.requestOptions = {
  25. host: clientRequestUrl.hostname,
  26. method: clientRequest.method,
  27. port: clientRequestUrl.port || ( this.ssl ? 443 : 80 )
  28. path: clientRequestUrl.path || '/',
  29. headers: clientRequest.headers
  30. };
  31. this.handle( );
  32. } else {
  33. clientResponse.end( 'Need url!' );
  34. }
  35. }
  36. Request.prototype = {
  37. handle: function ( ) {
  38. var that = this;
  39. var clientResponse = that.clientResponse;
  40. var clientRequest = that.clientRequest;console.log( this.requestOptions );
  41. var serverRequest = this.serverRequest = this.api.get( this.requestOptions, function ( serverResponse ) {
  42. that.serverResponse = serverResponse;
  43.  
  44. serverResponse.on( 'data', function ( chunk ) {
  45. clientResponse.write( chunk, 'binary' );
  46. } );
  47. serverResponse.on( 'end', function ( ) {
  48. clientResponse.end( );
  49. } );
  50.  
  51. var headers = serverResponse.headers;
  52. if ( headers.Location ) {console.log( headers.Location );
  53. //headers = Object.create( headers );
  54. headers.Location = url.parse( clientRequest.url ).pathname + '?url=' + headers.Location;
  55. console.log( headers.Location );
  56. }
  57.  
  58. clientResponse.writeHead( serverResponse.statusCode, serverResponse.headers );
  59.  
  60. clientRequest.on( 'data', function ( chunk ) {
  61. serverRequest.write( chunk, 'binary' );
  62. } );
  63. clientRequest.on( 'end', function ( ) {
  64. serverRequest.end( );
  65. } );
  66. } ).on( 'error', function ( e ) {
  67. if ( ++that.errors <= 5 ) {
  68. that.handle( );
  69. } else {
  70. clientResponse.end( 'Can\'t reach url: "' + that.url + '" (' + e + ')!' );
  71. }
  72. } );
  73. },
  74. errors: 0
  75. };
  76.  
  77. new Proxy( require( 'http' ), 8080 );
  78. new Proxy( require( 'https' ), 8243 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement