This repository has been archived by the owner on Apr 13, 2024. It is now read-only.
forked from premist/node-crossdomain-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·87 lines (67 loc) · 2.14 KB
/
server.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
/* (C) 2012 Premist aka Minku Lee.
LICENSE : https://github.com/premist/node-crossdomain-proxy/blob/master/LICENSE
*/
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var http = require('http');
var url = require('url');
var port = process.env.port || 1337;
http.createServer(function(proxyReq, proxyResp) {
var params = url.parse(proxyReq.url, true);
var URL = "http://" + params.query.src;
console.log("destination url=", URL);
var destParams = url.parse(URL);
util = require('util');
var reqOptions = {
host : destParams.host,
port : 80,
path : destParams.pathname,
method : "GET",
agent: false
};
if (reqOptions.host === 'undefined') {
return;
}
// console.dir(reqOptions);
var shasum = crypto.createHash('md5');
shasum.update(URL);
var cacheFileName = 'cache/' + shasum.digest('hex')+".jpeg";
// console.log(cacheFileName, URL);
// console.trace();
var headers = null;
path.exists(cacheFileName, function(exists) {
if (!exists) {
console.log("cache miss:",cacheFileName);
var ws = fs.createWriteStream(cacheFileName);
ws.on('close', function() {
var rs = fs.createReadStream(cacheFileName);
proxyResp.writeHead(200, headers);
util.pump(rs, proxyResp)
})
var req = http.request(reqOptions, function(res) {
headers = res.headers;
headers['Access-Control-Allow-Origin'] = '*';
headers['Access-Control-Allow-Headers'] = 'X-Requested-With';
util.pump(res, ws);
});
req.on('error', function(e) {
console.log('An error occured: ' + e.message);
proxyResp.writeHead(503);
proxyResp.write("Error!");
proxyResp.end();
});
req.end();
} else {
//read from fs
console.log('cache hit:', cacheFileName)
var rs = fs.createReadStream(cacheFileName);
headers = {};
headers['Access-Control-Allow-Origin'] = '*';
headers['Access-Control-Allow-Headers'] = 'X-Requested-With';
headers['Content-Type'] = 'image/jpeg';
proxyResp.writeHead(200, headers);
util.pump(rs, proxyResp)
}
});
}).listen(port);