forked from bitovi/funcunit
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
Latest commit
77 lines (67 loc) · 1.78 KB
/
Copy pathproxy.js
File metadata and controls
77 lines (67 loc) · 1.78 KB
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
// Usage: node funcunit/proxy.js --port=9999
varfs=require('fs'),
url=require('url')
path=require('path'),
http=require('http'),
port=9999;
// parse out command line options
process.argv.forEach(function(val){
if(val.indexOf('--port')==0){
port=parseInt(val.split('=')[1])
}
})
functionserveLocalFile(req,res){
varparsed=url.parse(req.url),
urlpath=parsed.pathname,
fullurl=path.normalize(path.join('.',urlpath));
if(~fullurl.indexOf('..')){
// don't send back any files above the directory we were invoked from
res.writeHead(404)
res.end()
}else{
// try to open the file locally
fs.readFile(fullurl,function(err,data){
if(err){
res.writeHead(404)
}else{
res.writeHead(200)
res.write(data)
}
res.end()
})
}
}
functionproxyToRemote(req,res){
varproxy=http.createClient(80,req.headers['host']),
preq=proxy.request(req.method,req.url,req.headers)
preq.on('response',function(pres){
// forward events from the proxy's response back to our client
pres.on('data',function(chunk){
res.write(chunk,'binary')
})
pres.on('end',function(){
res.end()
})
// write the proxy's status/headers back to our client
res.writeHead(pres.statusCode,pres.headers)
})
// forward events from our client's request onto the proxy
req.on('data',function(chunk){
preq.write(chunk,'binary')
})
req.on('end',function(){
preq.end()
})
}
http.createServer(function(req,res){
varparsed=url.parse(req.url),
path=parsed.pathname;
// anything under these directories will be served locally
if(path.indexOf('/funcunit')==0||
path.indexOf('/steal')==0||
path.indexOf('/test')==0){
serveLocalFile(req,res)
}else{
proxyToRemote(req,res)
}
}).listen(port)