Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var url = require( 'url' ),
- http = require( 'http' ),
- https = require( 'https' );
- function Proxy( api, port ) {
- var that = this;
- this.api = api;
- this.port = port;
- this.server = api.createServer( function ( clientRequest, clientResponse ) {
- that.request = new Request( clientRequest, clientResponse );
- } );
- this.server.listen( this.port );
- }
- Proxy.prototype = {
- stop: function ( ) {
- this.server.close( );
- }
- };
- function Request( clientRequest, clientResponse ) {
- this.clientRequest = clientRequest;
- this.clientResponse = clientResponse;
- this.$_GET = url.parse( clientRequest.url, true ).query;
- this.url = this.$_GET.url;
- if ( this.url ) {
- var clientRequestUrl = this.clientRequestUrl = url.parse( this.url );
- this.ssl = clientRequestUrl.protocol !== 'http:';
- this.api = this.ssl ? https : http;
- this.requestOptions = {
- host: clientRequestUrl.hostname,
- method: clientRequest.method,
- port: clientRequestUrl.port || ( this.ssl ? 443 : 80 ),
- path: clientRequestUrl.path || ('/'),
- headers: clientRequest.headers
- };
- this.handle( );
- } else {
- clientResponse.end( 'Need url!' );
- }
- }
- Request.prototype = {
- handle: function ( ) {
- var that = this;
- var clientResponse = that.clientResponse;
- var clientRequest = that.clientRequest;console.log( this.requestOptions );
- var serverRequest = this.serverRequest = this.api.get( this.requestOptions, function ( serverResponse ) {
- that.serverResponse = serverResponse;
- serverResponse.on( 'data', function ( chunk ) {
- clientResponse.write( chunk, 'binary' );
- } );
- serverResponse.on( 'end', function ( ) {
- clientResponse.end( );
- } );
- var headers = serverResponse.headers;
- if ( headers.Location ) {console.log( headers.Location );
- //headers = Object.create( headers );
- headers.Location = url.parse( clientRequest.url ).pathname + '?url=' + headers.Location;
- console.log( headers.Location );
- }
- clientResponse.writeHead( serverResponse.statusCode, serverResponse.headers );
- clientRequest.on( 'data', function ( chunk ) {
- serverRequest.write( chunk, 'binary' );
- } );
- clientRequest.on( 'end', function ( ) {
- serverRequest.end( );
- } );
- } ).on( 'error', function ( e ) {
- if ( ++that.errors <= 5 ) {
- that.handle( );
- } else {
- clientResponse.end( 'Can\'t reach url: "' + that.url + '" (' + e + ')!' );
- }
- } );
- },
- errors: 0
- };
- typeof proxy !== 'undefined' && proxy.stop( );
- proxy = new Proxy( require( 'http' ), 80 );
- //new Proxy( require( 'https' ), 8243 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement