Advertisement
Guest User

Untitled

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