-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxproxy
More file actions
76 lines (71 loc) · 2.31 KB
/
Copy pathxproxy
File metadata and controls
76 lines (71 loc) · 2.31 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
#!/usr/bin/env node
const express = require("express");
const path = require("path");
const fs = require("fs");
const os = require("os");
const _ = require("lodash");
const { createProxyMiddleware } = require("http-proxy-middleware");
const logFile = path.join(os.homedir(), '.xn_history', '.xn_proxy_history');
let port = 4000;
let pathRewrite;
const params = process.argv.slice(2);
const line = params.join(' ');
let index = params.indexOf('-p') === -1 ? params.indexOf('--port') : params.indexOf('-p');
if (index > -1 && params[index + 1]) {
port = params[index + 1];
params.splice(index, 2);
}
index = params.indexOf('-w') === -1 ? params.indexOf('--pathRewrite') : params.indexOf('-w');
if (index > -1 && params[index + 1]) {
pathRewrite = params[index + 1];
params.splice(index, 2);
}
const param = params[0];
if (param === '-h' || param === '--help' || !param) {
console.log('');
console.log('xproxy api@url');
console.log('');
console.log(' -h|--help: show help');
console.log(' -l|--list: show history list');
console.log(' -p|--port: set port for server');
console.log(' -w|--pathRewrite: for rewrite path e.g: xx:yy');
console.log(' xproxy api@http://localhost:5000 -w api:');
console.log(' notifyEntry@http://localhost:1112/xs_os/api/notify/notifyEntry');
process.exit(0);
}
if (param === '-l' || param === '--list') {
console.log(fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf-8') : '');
process.exit(0);
}
let list = param.split('@');
if (!list[1]) {
console.log('param must be api@url');
process.exit(0);
}
const format = p => p[0] === '/' ? p : `/${p}`;
const api = format(list[0]);
const target = list[1];
pathRewrite = pathRewrite ? {[format(pathRewrite.split(':')[0])]: format(pathRewrite.split(':')[1])} : {[`^${api}`]: `/`};
console.log({
api,
target,
changeOrigin: true,
pathRewrite,
});
const app = express();
app.use(
'/',
createProxyMiddleware({
target,
changeOrigin: true,
pathRewrite,
})
);
list = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf-8').split(/\n/) : [];
list = _.reverse(list);
list.unshift(`xproxy ${line}`);
list = _.uniq(list);
list = _.reverse(list);
fs.writeFileSync(logFile, list.join('\n'), 'utf-8');
app.listen(port);
console.log(`http://localhost:${port}${api} -> ${target}`);