-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.js
88 lines (68 loc) · 1.84 KB
/
proxy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var url = require('url'),
http = require('http'),
server = require('../../library/socket.io').listen(8080);
server.sockets.on('connection', function(socket) {
socket.on('push', function(options, callback) {
if(options.socket) {
var destination = server.sockets.socket(options.socket);
if(destination && options.message) {
destination.emit('push', options.message);
}
}
});
socket.on('request', function(options, callback) {
var headers = socket.handshake.headers,
options = options || {},
data = options.data || null,
urlData = {};
if(typeof options.url === 'string') {
urlData = url.parse(options.url || '');
}
if(options.headers) {
for(var key in options.headers) {
headers[key] = options.headers[key];
}
}
headers['x-socket-io-id'] = socket.id;
var port = options.port || 80,
path = options.path || urlData.path || '';
var hostname = options.hostname || urlData.hostname;
if(!hostname) {
urlData = url.parse(headers.referer);
hostname = urlData.hostname;
if(path.indexOf('/') !== 0) {
path = urlData.path + path;
}
}
var method = (options.method || (data ? 'POST' : 'GET')).toUpperCase();
var request = http.request({
hostname: hostname,
port: port,
path: path,
method: method,
headers: headers
});
request.on('response', function(response) {
var result = {
status: response.statusCode,
headers: response.headers,
success: true
};
var data = [];
response.on('data', function(responseData) {
data.push(responseData);
});
response.on('end', function() {
var responseData = data.join('');
result.responseText = responseData;
if(typeof callback === 'function') {
callback(result);
}
});
});
if(data) {
request.write(data);
}
request.end();
});
});