mirror of
https://github.com/http-party/node-http-proxy.git
synced 2025-12-08 20:59:18 +00:00
Compare commits
930 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9b96cd7251 | ||
|
|
335aeeba2f | ||
|
|
dba39668ba | ||
|
|
9bbe486c5e | ||
|
|
6e4bef4d1c | ||
|
|
d05624167c | ||
|
|
244303b994 | ||
|
|
b4028ba78b | ||
|
|
77a98159d2 | ||
|
|
c662f9ebcd | ||
|
|
806e4927c9 | ||
|
|
c8fa599983 | ||
|
|
0d9ed366b1 | ||
|
|
9d75b981a1 | ||
|
|
192b2b980b | ||
|
|
4a657a7126 | ||
|
|
7a154f81d1 | ||
|
|
749eec65c3 | ||
|
|
e588213644 | ||
|
|
59c4403e9d | ||
|
|
dd1d08b631 | ||
|
|
16d4f8a951 | ||
|
|
fc93520d74 | ||
|
|
7e4a0e511b | ||
|
|
a9b09cce43 | ||
|
|
b00911c937 | ||
|
|
36bfe566a7 | ||
|
|
91fee3e943 | ||
|
|
235f0aa047 | ||
|
|
acdbec09c6 | ||
|
|
569e2ac4fb | ||
|
|
cb3171abfa | ||
|
|
a3fe02d651 | ||
|
|
42e8e1e099 | ||
|
|
e94d52973a | ||
|
|
4a37175a52 | ||
|
|
e5c02b8a8a | ||
|
|
2c44039a7c | ||
|
|
8097ae237e | ||
|
|
abf882e03c | ||
|
|
bab02e909e | ||
|
|
c9a556cfa5 | ||
|
|
6f88caf6e4 | ||
|
|
d2f9db8241 | ||
|
|
8231984fb0 | ||
|
|
81d58c531b | ||
|
|
d533a1be43 | ||
|
|
89f9ef87e0 | ||
|
|
c5d8466483 | ||
|
|
107c18720c | ||
|
|
de1b80851a | ||
|
|
bc6a23709c | ||
|
|
f5c2381395 | ||
|
|
50f58b4cd9 | ||
|
|
2c98416ac2 | ||
|
|
543636d0f6 | ||
|
|
a4bccc332d | ||
|
|
f4ff1006b9 | ||
|
|
09dcb98456 | ||
|
|
812757541d | ||
|
|
c979ba9f2c | ||
|
|
e6f24ba617 | ||
|
|
d73f1ee873 | ||
|
|
a539f3cbc1 | ||
|
|
d4d85ac5c4 | ||
|
|
c1fb596b85 | ||
|
|
961f457622 | ||
|
|
ac1a01b1f3 | ||
|
|
8cb451f20c | ||
|
|
c252b32f6c | ||
|
|
927357bedc | ||
|
|
4edbb62cc5 | ||
|
|
69cf892519 | ||
|
|
2f7f03778c | ||
|
|
d8223884f6 | ||
|
|
d0f1dfeb82 | ||
|
|
220f5fb795 | ||
|
|
d48f67eb90 | ||
|
|
61c2889109 | ||
|
|
fbc266809c | ||
|
|
8eddf45f2a | ||
|
|
f5217d6c20 | ||
|
|
2d01edc5a5 | ||
|
|
d0a1588639 | ||
|
|
912cd3acae | ||
|
|
84087208dd | ||
|
|
b98c75b1ff | ||
|
|
b781af641a | ||
|
|
cbd5777060 | ||
|
|
d8fb344715 | ||
|
|
1e52f660f0 | ||
|
|
9d06ca99d3 | ||
|
|
d0e000e1f9 | ||
|
|
183b5bb4fc | ||
|
|
3a347af543 | ||
|
|
fcfb0b37f6 | ||
|
|
42df703830 | ||
|
|
3e966361bc | ||
|
|
5082acc067 | ||
|
|
433a7408cf | ||
|
|
6baf1498cb | ||
|
|
284903d379 | ||
|
|
b223275ebb | ||
|
|
ecdfff408f | ||
|
|
28cecb5a96 | ||
|
|
bdb3492b21 | ||
|
|
a4b2857216 | ||
|
|
820fc5987c | ||
|
|
f345a1ac2d | ||
|
|
018352955e | ||
|
|
f8d605d53f | ||
|
|
c1440b58f1 | ||
|
|
ef86b50427 | ||
|
|
e1b2f4c31b | ||
|
|
820f198729 | ||
|
|
d2df053677 | ||
|
|
7357200334 | ||
|
|
d19be83858 | ||
|
|
570cf3b4f9 | ||
|
|
5c46e4b754 | ||
|
|
25e56d0182 | ||
|
|
9d9fa940cf | ||
|
|
2831d9a4f9 | ||
|
|
a379d160f3 | ||
|
|
7aed1f4559 | ||
|
|
bfcab93d8d | ||
|
|
7bad3fbca4 | ||
|
|
268994ea45 | ||
|
|
58c0fdc761 | ||
|
|
d73b0d312a | ||
|
|
a76e226221 | ||
|
|
db576d75c1 | ||
|
|
e017fa8189 | ||
|
|
646a7493a4 | ||
|
|
3b39d2c3dc | ||
|
|
0cb1d3c68e | ||
|
|
f9540de7b1 | ||
|
|
f2093b5313 | ||
|
|
41414a56a1 | ||
|
|
6371231086 | ||
|
|
6c83980f29 | ||
|
|
e4760727f1 | ||
|
|
222a4d0fa1 | ||
|
|
6106d4c32f | ||
|
|
cd1d7776e8 | ||
|
|
642e9cc2cb | ||
|
|
eea79cab53 | ||
|
|
f82ce18d2f | ||
|
|
470475b896 | ||
|
|
2a5e69d48c | ||
|
|
9ea1e89a2f | ||
|
|
ab42124d54 | ||
|
|
5d593e8ef1 | ||
|
|
64fa520789 | ||
|
|
b5a6d0e583 | ||
|
|
0bc4c783ca | ||
|
|
9752652e76 | ||
|
|
a05fc2d169 | ||
|
|
60baca5aed | ||
|
|
6b65c428b3 | ||
|
|
eb97bf5423 | ||
|
|
ec64e4f597 | ||
|
|
e666a4e07d | ||
|
|
c86ae51bb9 | ||
|
|
302d981dd2 | ||
|
|
30e3b371de | ||
|
|
cea0e8676b | ||
|
|
3d2350c54f | ||
|
|
ca73208749 | ||
|
|
da674ec4df | ||
|
|
855cebdac4 | ||
|
|
8bfd90c4d9 | ||
|
|
931f73dc98 | ||
|
|
349b843731 | ||
|
|
2e3eb0950d | ||
|
|
1f4fccd2c6 | ||
|
|
ecbba1a008 | ||
|
|
fe3dd8363f | ||
|
|
38864d0167 | ||
|
|
76051032e7 | ||
|
|
7e82a04a16 | ||
|
|
1912b62ddb | ||
|
|
3f997b9289 | ||
|
|
7e6c66a7e4 | ||
|
|
d26ef56e1b | ||
|
|
607f96c00c | ||
|
|
18c77cafc7 | ||
|
|
934e6c4d54 | ||
|
|
0db8f195d7 | ||
|
|
0bd446c680 | ||
|
|
a6ae6c4997 | ||
|
|
1b89bc9a76 | ||
|
|
c6dfb04a67 | ||
|
|
6201ac76f7 | ||
|
|
5f14bcaa70 | ||
|
|
0ee314c436 | ||
|
|
c33d1616cd | ||
|
|
1dabda241f | ||
|
|
5a969d077b | ||
|
|
21b30b754d | ||
|
|
aa8f3e9a6e | ||
|
|
ab37a224aa | ||
|
|
d145152655 | ||
|
|
87a92a7280 | ||
|
|
507f818df5 | ||
|
|
e907d7bb2a | ||
|
|
7298510e91 | ||
|
|
63c9262df5 | ||
|
|
ff1626f071 | ||
|
|
df158bfc53 | ||
|
|
f55ffa356a | ||
|
|
ab5c3e5c81 | ||
|
|
245d73ae6c | ||
|
|
6d074eff47 | ||
|
|
26029ba7ac | ||
|
|
14415a5074 | ||
|
|
62e4b75101 | ||
|
|
7f2f3ac35c | ||
|
|
9eefd4678e | ||
|
|
9ece52fac4 | ||
|
|
32aa10dfe2 | ||
|
|
c82c9ece8a | ||
|
|
3311106c2c | ||
|
|
402ab05734 | ||
|
|
f0db5b3f70 | ||
|
|
f30486195c | ||
|
|
ea0a4ded80 | ||
|
|
8a8a894092 | ||
|
|
c62610e8e4 | ||
|
|
05d18a4e1b | ||
|
|
8bff3ddc12 | ||
|
|
26537866b3 | ||
|
|
f92a1b6839 | ||
|
|
c1a94176a8 | ||
|
|
099eb86948 | ||
|
|
4bd3c4671f | ||
|
|
6a330ff904 | ||
|
|
89f9ca1e89 | ||
|
|
c04485671a | ||
|
|
2086e4917c | ||
|
|
71a06aab02 | ||
|
|
501e8c2a9b | ||
|
|
81874f795b | ||
|
|
75a9a2de61 | ||
|
|
aeb42a3614 | ||
|
|
56a7b77645 | ||
|
|
9c0b8697bc | ||
|
|
410a8ce94c | ||
|
|
d98d9516ea | ||
|
|
70ed1c4273 | ||
|
|
361d4e3b00 | ||
|
|
276f65a3b8 | ||
|
|
8d68ac0e0f | ||
|
|
48ae5d828c | ||
|
|
95a588706b | ||
|
|
3194d819b4 | ||
|
|
8a24a1e18f | ||
|
|
add81338a9 | ||
|
|
daf66a7a88 | ||
|
|
aba505d159 | ||
|
|
84036e9ddd | ||
|
|
daa2ce0ee3 | ||
|
|
69a693034e | ||
|
|
9ba8311343 | ||
|
|
709b3e9656 | ||
|
|
3f19e6e178 | ||
|
|
7c5e40a429 | ||
|
|
eb95660822 | ||
|
|
4a2b870cc9 | ||
|
|
fa797fca90 | ||
|
|
57329b6327 | ||
|
|
d1eabccf93 | ||
|
|
60bd697051 | ||
|
|
1af8224cc1 | ||
|
|
43641b00b3 | ||
|
|
70fa8ad58c | ||
|
|
796ab0bcc5 | ||
|
|
f70015f001 | ||
|
|
f64954a08b | ||
|
|
9f684d0439 | ||
|
|
3768cce4ca | ||
|
|
d46e876e27 | ||
|
|
0378b03e53 | ||
|
|
04c45a022c | ||
|
|
9577a0faf2 | ||
|
|
fcdbf46e4d | ||
|
|
c62766391e | ||
|
|
43c6f0c7c0 | ||
|
|
b065d92908 | ||
|
|
bcd8a564a8 | ||
|
|
77305489d9 | ||
|
|
f0bf741815 | ||
|
|
10a294af4d | ||
|
|
232258b6ec | ||
|
|
9210b56c9e | ||
|
|
000eb533de | ||
|
|
2aa3b84d7b | ||
|
|
a4ca578b44 | ||
|
|
e7d50b1a37 | ||
|
|
c0a796b3e3 | ||
|
|
90d40d6a6a | ||
|
|
45cf95a82e | ||
|
|
42c35aedca | ||
|
|
ec683b924b | ||
|
|
65a21bce6d | ||
|
|
51eeebef68 | ||
|
|
554f59c518 | ||
|
|
73e8a4cdd5 | ||
|
|
3ab6e9591e | ||
|
|
a934cb6a46 | ||
|
|
107b9da256 | ||
|
|
73d865bc9f | ||
|
|
df12aeb12d | ||
|
|
ed73f06ed3 | ||
|
|
d5c656bceb | ||
|
|
dceef407a1 | ||
|
|
e44fabe58a | ||
|
|
9a534c6ff6 | ||
|
|
d1facd52c3 | ||
|
|
5568cb5575 | ||
|
|
6ac05259ca | ||
|
|
0e64568b4e | ||
|
|
fc73828035 | ||
|
|
814fbd254d | ||
|
|
a65021d52b | ||
|
|
511b7b3d47 | ||
|
|
6b83ae47bb | ||
|
|
d16062bba2 | ||
|
|
49a0de1e7c | ||
|
|
05f0b891a6 | ||
|
|
261742a429 | ||
|
|
f92f7aea9b | ||
|
|
8be9d945d0 | ||
|
|
0a6b424e2c | ||
|
|
37036dd325 | ||
|
|
a3d02196c5 | ||
|
|
63c53a1772 | ||
|
|
3e8ee042fb | ||
|
|
db5f2954b2 | ||
|
|
ed9e12b0ed | ||
|
|
5f838541cb | ||
|
|
e336b52629 | ||
|
|
7104a7c023 | ||
|
|
d1baa3684e | ||
|
|
e50846b967 | ||
|
|
9df4bc1e12 | ||
|
|
f6bac7b257 | ||
|
|
48d46e6750 | ||
|
|
7b79a7409a | ||
|
|
4193d3bd74 | ||
|
|
159ca83652 | ||
|
|
0f243516e1 | ||
|
|
431aba79d8 | ||
|
|
7cb98a4e41 | ||
|
|
5ebf9833c8 | ||
|
|
1385635e18 | ||
|
|
1213e46b1b | ||
|
|
c472527ea6 | ||
|
|
ccad177954 | ||
|
|
896ee7c9c3 | ||
|
|
8aa7c519b1 | ||
|
|
d637b96420 | ||
|
|
4947484806 | ||
|
|
c54278bd3b | ||
|
|
61c8734e8b | ||
|
|
77a1cff9bc | ||
|
|
d908e2ad61 | ||
|
|
4f07dc220d | ||
|
|
97ceeb37d0 | ||
|
|
8b48a9fdab | ||
|
|
c6b7a7919f | ||
|
|
7e5feec34f | ||
|
|
d658c9fa39 | ||
|
|
eca765a856 | ||
|
|
07fceb7c7a | ||
|
|
ece85b4e1b | ||
|
|
5251a238e7 | ||
|
|
89a22bc003 | ||
|
|
a7b16eb136 | ||
|
|
c22610af75 | ||
|
|
99f757251b | ||
|
|
e633b0f7e4 | ||
|
|
10670540ac | ||
|
|
68fa17bbca | ||
|
|
7923cf3c6b | ||
|
|
81daf26a43 | ||
|
|
80f645c7c0 | ||
|
|
4bdc3e4f45 | ||
|
|
4c3ba74c4e | ||
|
|
daad4703f3 | ||
|
|
b60673522b | ||
|
|
4ecc6e26ce | ||
|
|
8004f4e5fc | ||
|
|
3b2178d1f7 | ||
|
|
0b223abb65 | ||
|
|
7a53ec2fd6 | ||
|
|
96ea631fb6 | ||
|
|
3e47c2485c | ||
|
|
c5ec1836b2 | ||
|
|
e936d186b6 | ||
|
|
68c5512303 | ||
|
|
689459fe46 | ||
|
|
53a2653b5e | ||
|
|
3330e125aa | ||
|
|
d6d2d0c882 | ||
|
|
d4942e52e7 | ||
|
|
d23353d980 | ||
|
|
4351ed1c86 | ||
|
|
0ba4fa8e5e | ||
|
|
969a623542 | ||
|
|
0b642d4cf7 | ||
|
|
a4ee8f9d82 | ||
|
|
2c8edc170d | ||
|
|
c47adac391 | ||
|
|
c17b591b7d | ||
|
|
6fa23e11f6 | ||
|
|
182c76cd23 | ||
|
|
e5991519db | ||
|
|
840f6d8d29 | ||
|
|
a81dd8d53e | ||
|
|
8eb6780f87 | ||
|
|
1333c0cc62 | ||
|
|
2d42709c32 | ||
|
|
d4e91ebc33 | ||
|
|
7e8041d2b6 | ||
|
|
8332e74420 | ||
|
|
145798062e | ||
|
|
7c8ecc8ea8 | ||
|
|
25bb3bfa70 | ||
|
|
bc12ca3939 | ||
|
|
781c038f2b | ||
|
|
d60f1a9353 | ||
|
|
162a42f58f | ||
|
|
9243444ac0 | ||
|
|
db12f6c24e | ||
|
|
16828a9915 | ||
|
|
e2a5d513ca | ||
|
|
d83fdf69a1 | ||
|
|
bc236d7e95 | ||
|
|
c82ff2c3c0 | ||
|
|
d7064f2e1e | ||
|
|
de3ff11656 | ||
|
|
2142c506e0 | ||
|
|
e592c53d1a | ||
|
|
d85ccdd333 | ||
|
|
831a44b3c8 | ||
|
|
ed8c9eeba9 | ||
|
|
588327c2c4 | ||
|
|
e02317ce86 | ||
|
|
b726116134 | ||
|
|
7e44d3669b | ||
|
|
bdeabb767a | ||
|
|
cfd417de23 | ||
|
|
c4d56a5faf | ||
|
|
4d65280ea3 | ||
|
|
36389384cb | ||
|
|
9e74a633a7 | ||
|
|
97e4600e94 | ||
|
|
03880d8d06 | ||
|
|
0393b5da99 | ||
|
|
ae0faef5aa | ||
|
|
ef8150af95 | ||
|
|
584ce76e75 | ||
|
|
10c0f11b68 | ||
|
|
83367e7e91 | ||
|
|
cb7af4f4d7 | ||
|
|
dcb873ad99 | ||
|
|
54eceb4a86 | ||
|
|
7a3f6dfbcc | ||
|
|
04c10113f7 | ||
|
|
961d2f9400 | ||
|
|
bbe3bfdf98 | ||
|
|
31d919b0a3 | ||
|
|
6a6dfbb79d | ||
|
|
a467b7b4a9 | ||
|
|
fd42dcef01 | ||
|
|
a2b1f0a4c9 | ||
|
|
d0862aff0c | ||
|
|
cde08fb2ee | ||
|
|
590bb604da | ||
|
|
b8c6397a94 | ||
|
|
dda6f7a45a | ||
|
|
8085178dc2 | ||
|
|
1204a35e46 | ||
|
|
f720e36b42 | ||
|
|
33a2462d28 | ||
|
|
e3f8d5fdbe | ||
|
|
a1b25a123b | ||
|
|
920f1e7707 | ||
|
|
c75d06c5f9 | ||
|
|
d60353f80b | ||
|
|
02df9a33c5 | ||
|
|
881c7e62e0 | ||
|
|
cc09ae6a34 | ||
|
|
7c72f3b407 | ||
|
|
0bfb9be418 | ||
|
|
5d66ce11bb | ||
|
|
5e130de854 | ||
|
|
babdf531fe | ||
|
|
2bf20d61d5 | ||
|
|
52ecd52ee5 | ||
|
|
9b3e1eb247 | ||
|
|
90fb01d38a | ||
|
|
1d1ee88582 | ||
|
|
e4450132e2 | ||
|
|
bbe2b2788a | ||
|
|
86750c7e59 | ||
|
|
c65ffbb976 | ||
|
|
a7042132c8 | ||
|
|
b333e63648 | ||
|
|
c9f5772fc1 | ||
|
|
a9f9e21eda | ||
|
|
3d8e5383cd | ||
|
|
5a1504f076 | ||
|
|
c7924e01f9 | ||
|
|
601dbcbfe9 | ||
|
|
b79bd29d5e | ||
|
|
a51b062278 | ||
|
|
8269eca2bb | ||
|
|
1436b715ae | ||
|
|
bb0d28c587 | ||
|
|
f7f5fa727e | ||
|
|
455f97e14c | ||
|
|
17399e7c3e | ||
|
|
0aeaba7fe6 | ||
|
|
94ec6fa5ce | ||
|
|
32a40889ce | ||
|
|
32dcb0449c | ||
|
|
4a517fbe6e | ||
|
|
5dcdf2b36c | ||
|
|
7ad5c0f993 | ||
|
|
39b0c46a69 | ||
|
|
a350fadea6 | ||
|
|
1b5fb1d8fc | ||
|
|
12cda561af | ||
|
|
f566a42e51 | ||
|
|
4ee96ddd66 | ||
|
|
1c7ace26c5 | ||
|
|
7d840d3515 | ||
|
|
427d8d8536 | ||
|
|
13741a823f | ||
|
|
69f126b34c | ||
|
|
72a89eab8b | ||
|
|
1ceea3e5f9 | ||
|
|
f36cb4d5a1 | ||
|
|
ca092635e7 | ||
|
|
8663ac1c43 | ||
|
|
afc4d0931f | ||
|
|
6b61878759 | ||
|
|
16a4d9da11 | ||
|
|
2c10f256b6 | ||
|
|
611a1b1961 | ||
|
|
031452e400 | ||
|
|
9efa40a9d2 | ||
|
|
8eff1a1f26 | ||
|
|
10a0db4f0d | ||
|
|
0602500230 | ||
|
|
02007ed0fb | ||
|
|
40902506af | ||
|
|
7e25bded27 | ||
|
|
c01fd2c54e | ||
|
|
dc9d7e5452 | ||
|
|
7b9169c8c5 | ||
|
|
1cb967b90a | ||
|
|
5bb83b967e | ||
|
|
275a5192fa | ||
|
|
f1aeb0500c | ||
|
|
da9de7034a | ||
|
|
38e6d7cd54 | ||
|
|
469b0d4e9f | ||
|
|
9f3508805a | ||
|
|
dfdedf23b7 | ||
|
|
bd106d69f0 | ||
|
|
07091b5077 | ||
|
|
edd8e2f04e | ||
|
|
ef946a7697 | ||
|
|
268afe34bb | ||
|
|
1b867a7f59 | ||
|
|
29afab4488 | ||
|
|
e08d4edad3 | ||
|
|
60de543d04 | ||
|
|
adc5be020c | ||
|
|
0637322d96 | ||
|
|
4d3a4e1ee7 | ||
|
|
dd0f7b8876 | ||
|
|
d7078e2fdd | ||
|
|
ee3cc38066 | ||
|
|
aaff1966e4 | ||
|
|
57abb7f26c | ||
|
|
8b05626eed | ||
|
|
98f29bdcfc | ||
|
|
4c2f2f3b9a | ||
|
|
c9945dd370 | ||
|
|
5823842194 | ||
|
|
d1663549ec | ||
|
|
18341d5597 | ||
|
|
26c4c43a06 | ||
|
|
3c91ed3d26 | ||
|
|
46fe81e11a | ||
|
|
92de6a6f95 | ||
|
|
6e77cd3909 | ||
|
|
7599cee3fd | ||
|
|
dad211e71c | ||
|
|
63b016c8ef | ||
|
|
ec981c5b74 | ||
|
|
c4ddc4edd3 | ||
|
|
886a870707 | ||
|
|
8c8c455541 | ||
|
|
031aa0fbf3 | ||
|
|
07cfa6b981 | ||
|
|
7d71a867a8 | ||
|
|
6a03e5f7cf | ||
|
|
2a593664a5 | ||
|
|
893100972c | ||
|
|
79a14acfd2 | ||
|
|
f97c0c6167 | ||
|
|
1a7bef0cda | ||
|
|
e45bfd66a2 | ||
|
|
a74cd85c8a | ||
|
|
4a4607d075 | ||
|
|
0fb33810f5 | ||
|
|
c9cd6d2ad3 | ||
|
|
8b3fe32f6a | ||
|
|
e0faaaf811 | ||
|
|
1993faf8a4 | ||
|
|
3a39e444ff | ||
|
|
07551c63e4 | ||
|
|
79f7f99528 | ||
|
|
4480699d3a | ||
|
|
a6256cac1d | ||
|
|
b85aa16e75 | ||
|
|
27df8d72ad | ||
|
|
abf1d90fdf | ||
|
|
c9612798f1 | ||
|
|
8fc3389367 | ||
|
|
f4e9945856 | ||
|
|
2fac7b9b00 | ||
|
|
c02b721321 | ||
|
|
d40e4beb62 | ||
|
|
356f43d719 | ||
|
|
d4f0da898e | ||
|
|
9ab8749a9b | ||
|
|
bd3df45010 | ||
|
|
2e7343d728 | ||
|
|
6a4294cbdf | ||
|
|
4f24664e8a | ||
|
|
cedc5c4bd2 | ||
|
|
335af81d02 | ||
|
|
a255f984fe | ||
|
|
16eacfa961 | ||
|
|
004a46c09d | ||
|
|
34f16e7464 | ||
|
|
d05af4af60 | ||
|
|
8273cb6461 | ||
|
|
4d13156721 | ||
|
|
ebbba73eda | ||
|
|
2fd748fb61 | ||
|
|
e1d384e769 | ||
|
|
5ff2b6e1a1 | ||
|
|
f5e1844abd | ||
|
|
0c753234c0 | ||
|
|
de0928f616 | ||
|
|
7fc39d77f4 | ||
|
|
59b71c033f | ||
|
|
985025c90f | ||
|
|
98f5c462ea | ||
|
|
daf53bd753 | ||
|
|
a29b5e8e28 | ||
|
|
9c13ad46e4 | ||
|
|
3763dc935f | ||
|
|
71183bf30b | ||
|
|
8665f3cc60 | ||
|
|
4335f49b0e | ||
|
|
ea10bb22d9 | ||
|
|
2620f06e2d | ||
|
|
3ebc795c33 | ||
|
|
4e42354e77 | ||
|
|
35ba0db554 | ||
|
|
c9b6895c5e | ||
|
|
701dc698e3 | ||
|
|
ea5e214522 | ||
|
|
c78356e9cf | ||
|
|
c68e038912 | ||
|
|
133115c976 | ||
|
|
ad213106d0 | ||
|
|
ea0587a8f9 | ||
|
|
5d515e4728 | ||
|
|
5e6be6ccf5 | ||
|
|
a1607c1684 | ||
|
|
46b078a98d | ||
|
|
10f6b05775 | ||
|
|
2c3650746c | ||
|
|
89d43c20dd | ||
|
|
476cbe741f | ||
|
|
9be0af3166 | ||
|
|
a89e2f2688 | ||
|
|
6a278b3dd8 | ||
|
|
3130665d9f | ||
|
|
4c1a2c1416 | ||
|
|
b1c4bd61e8 | ||
|
|
3b86a7aae3 | ||
|
|
4c130f5dac | ||
|
|
9cecd97153 | ||
|
|
440013c263 | ||
|
|
ba65a485fc | ||
|
|
ef66833c4d | ||
|
|
af9eb06e47 | ||
|
|
28a3b0a6f0 | ||
|
|
ecb547223f | ||
|
|
ffe74ed299 | ||
|
|
eee6babc98 | ||
|
|
c6da760ca9 | ||
|
|
a681493371 | ||
|
|
2055d0c8ec | ||
|
|
013cb2e0c2 | ||
|
|
deca7565c5 | ||
|
|
64efa7f929 | ||
|
|
83fbd42506 | ||
|
|
9672b99271 | ||
|
|
8d8739999f | ||
|
|
31fc94aa5e | ||
|
|
133240937d | ||
|
|
916d44e3d2 | ||
|
|
025adc2912 | ||
|
|
8b38c994a9 | ||
|
|
c686ac7b01 | ||
|
|
603106a13d | ||
|
|
ee6bbe0024 | ||
|
|
3b84e27ab4 | ||
|
|
43e5f33320 | ||
|
|
d2888c83f5 | ||
|
|
15afc23a27 | ||
|
|
26d3646ff2 | ||
|
|
223eacda85 | ||
|
|
edfe869159 | ||
|
|
6cd78f6af9 | ||
|
|
2a61ec85bd | ||
|
|
7bc1a628fe | ||
|
|
b81d9b71da | ||
|
|
6797a2705a | ||
|
|
2bd9cd9adb | ||
|
|
8b3cfdaaea | ||
|
|
0fd5884a0f | ||
|
|
22639b3781 | ||
|
|
03dbe115c2 | ||
|
|
8a88774ecf | ||
|
|
b8c27ed565 | ||
|
|
886a395429 | ||
|
|
9042665ea9 | ||
|
|
41c9a9caad | ||
|
|
74ec175715 | ||
|
|
3531fd609a | ||
|
|
fefbf04ac0 | ||
|
|
3d618777ea | ||
|
|
a487dc9b58 | ||
|
|
4d7e8a808d | ||
|
|
ebfdbede31 | ||
|
|
5df6e7bdb8 | ||
|
|
1df2b30e84 | ||
|
|
213e03c998 | ||
|
|
d4cb9dad6c | ||
|
|
4c8e1d96a3 | ||
|
|
2e7d8a88f4 | ||
|
|
eafdc744b6 | ||
|
|
e925e4928f | ||
|
|
a89a5b8088 | ||
|
|
698b01da8e | ||
|
|
a64cec0be9 | ||
|
|
bf04bbde8f | ||
|
|
1db9542723 | ||
|
|
850171cdc4 | ||
|
|
4f6387c17f | ||
|
|
cee27feedd | ||
|
|
812868ddfc | ||
|
|
1783ab0625 | ||
|
|
a454666e7a | ||
|
|
c4a7b15843 | ||
|
|
fd648a5290 | ||
|
|
82da8535c5 | ||
|
|
89459bfd32 | ||
|
|
24b84068ea | ||
|
|
0d00b06af3 | ||
|
|
13c34d09b2 | ||
|
|
67539519fa | ||
|
|
29e6e748f7 | ||
|
|
2d75510d82 | ||
|
|
36226daa2e | ||
|
|
46c184cb08 | ||
|
|
4999b20b84 | ||
|
|
02b914d609 | ||
|
|
f28c62c815 | ||
|
|
0273958b0a | ||
|
|
04ce49c5b2 | ||
|
|
1cc1f90527 | ||
|
|
54f83717b2 | ||
|
|
7e854d778b | ||
|
|
828dbebcaa | ||
|
|
55286a7c49 | ||
|
|
e2dc7f9693 | ||
|
|
4ae7a5b840 | ||
|
|
0b6c7f5f7e | ||
|
|
fd16aeb4f8 | ||
|
|
bf7e328fb8 | ||
|
|
415d4ed908 | ||
|
|
06e78f2747 | ||
|
|
ccd8f840b2 | ||
|
|
0933f1c598 | ||
|
|
81f6095cf0 | ||
|
|
45d67f42cb | ||
|
|
27fa708449 | ||
|
|
e9a3a3012c | ||
|
|
64c974755d | ||
|
|
df650d11dd | ||
|
|
b5847733cd | ||
|
|
ca37ad7436 | ||
|
|
0532995dfa | ||
|
|
f223ce8b4e | ||
|
|
27316e22e8 | ||
|
|
c4d185dca9 | ||
|
|
5d839dd5f8 | ||
|
|
ed06af97ef | ||
|
|
4d7eaff65b | ||
|
|
4fc1ee85d3 | ||
|
|
843901eeeb | ||
|
|
b26b434e9f | ||
|
|
11315e63fa | ||
|
|
4358a4c122 | ||
|
|
1a014f96dd | ||
|
|
5842d0ee7d | ||
|
|
62013281b8 | ||
|
|
f1611ec8dc | ||
|
|
fd7fcd8dec | ||
|
|
f20b3740b1 | ||
|
|
4f2bc58431 | ||
|
|
99ee54259e | ||
|
|
e9fd3f43d7 | ||
|
|
a088efdb04 | ||
|
|
7fa6599f4f | ||
|
|
b979cb32a1 | ||
|
|
e15db4fb50 | ||
|
|
91bb2a9106 | ||
|
|
73e415a226 | ||
|
|
868f7e7a28 | ||
|
|
5055689a11 | ||
|
|
c81bae2fdd | ||
|
|
6f8ad3b8c3 | ||
|
|
3828616816 | ||
|
|
ea7fea6272 | ||
|
|
8358ef8a2b | ||
|
|
c4124da4f2 | ||
|
|
bc98c0dbce | ||
|
|
feb324b0d4 | ||
|
|
275109b2f8 | ||
|
|
c26ab5e46f | ||
|
|
d7f15d02f7 | ||
|
|
35d2088c96 | ||
|
|
48d4a8b263 | ||
|
|
5c3d41bf4e | ||
|
|
38bd906f2b | ||
|
|
b76680b045 | ||
|
|
68cebbe0e7 | ||
|
|
e109eba972 | ||
|
|
219b0ff8f8 | ||
|
|
a4079c6a1c | ||
|
|
2ccc5c73ea | ||
|
|
004be38048 | ||
|
|
4e1ca6e618 | ||
|
|
13389db1be | ||
|
|
f79f3adf02 | ||
|
|
f298411f76 | ||
|
|
5ac987857c | ||
|
|
f1c0be3f0b | ||
|
|
7bf8d4a7be | ||
|
|
4d43d81e5c | ||
|
|
80c216df0c | ||
|
|
a6353897cd | ||
|
|
7648fe50c1 | ||
|
|
25a9e2d217 | ||
|
|
60ff181af9 | ||
|
|
98bbe541e4 | ||
|
|
d7461f3206 | ||
|
|
c0857f2d59 | ||
|
|
b3b5cce3ae | ||
|
|
82060a5343 | ||
|
|
31a8c6800d | ||
|
|
87999d0288 | ||
|
|
543f214361 | ||
|
|
8ca5d83497 | ||
|
|
63dfc7f175 | ||
|
|
9f05e6c567 | ||
|
|
d1b19a1205 | ||
|
|
5b52c89694 | ||
|
|
86b4122323 | ||
|
|
6655e01642 | ||
|
|
8d701bb20b | ||
|
|
e2dccbca48 | ||
|
|
f086692619 | ||
|
|
411bb51cc6 | ||
|
|
553e7fbc33 | ||
|
|
621f9b425a | ||
|
|
1e33434fcc | ||
|
|
30dac898f3 | ||
|
|
3ab02f3ad7 | ||
|
|
c03a450d9b | ||
|
|
2061c71366 | ||
|
|
d6ea3a425c | ||
|
|
152d258ea0 | ||
|
|
6a9751eb0d | ||
|
|
c98ccb40e9 | ||
|
|
c5dc9295c7 | ||
|
|
f27d26f451 | ||
|
|
b4d41c3628 | ||
|
|
65b7872e6a | ||
|
|
f004788098 | ||
|
|
dd8319972c | ||
|
|
c60c6a27f6 | ||
|
|
3dfba2ba45 | ||
|
|
182dcd3455 | ||
|
|
6e65c20017 | ||
|
|
c83d88ee88 | ||
|
|
9f923325d0 | ||
|
|
9e630daf81 | ||
|
|
63ac925260 | ||
|
|
cdb45247ca | ||
|
|
7feee194f8 | ||
|
|
a72696533b | ||
|
|
729496d289 | ||
|
|
91e9bb9070 | ||
|
|
4d50915373 | ||
|
|
f188f4ffd8 |
6
.auto-changelog
Normal file
6
.auto-changelog
Normal file
@ -0,0 +1,6 @@
|
||||
{
|
||||
"output": "CHANGELOG.md",
|
||||
"template": "keepachangelog",
|
||||
"unreleased": true,
|
||||
"commitLimit": false
|
||||
}
|
||||
1
.gitattributes
vendored
Normal file
1
.gitattributes
vendored
Normal file
@ -0,0 +1 @@
|
||||
package-lock.json binary
|
||||
11
.gitignore
vendored
11
.gitignore
vendored
@ -1,3 +1,10 @@
|
||||
config.json
|
||||
node_modules/
|
||||
node_modules
|
||||
*.swp
|
||||
cov
|
||||
atest.js
|
||||
notes
|
||||
primus-proxy.js
|
||||
tes.js
|
||||
npm-debug.log
|
||||
.nyc_output
|
||||
coverage
|
||||
|
||||
9
.npmignore
Normal file
9
.npmignore
Normal file
@ -0,0 +1,9 @@
|
||||
test
|
||||
examples
|
||||
doc
|
||||
benchmark
|
||||
coverage
|
||||
.nyc_output
|
||||
.travis.yml
|
||||
CHANGELOG.md
|
||||
UPGRADING.md
|
||||
12
.travis.yml
Normal file
12
.travis.yml
Normal file
@ -0,0 +1,12 @@
|
||||
sudo: false
|
||||
language: node_js
|
||||
node_js:
|
||||
- "8"
|
||||
- "10"
|
||||
- "12"
|
||||
script:
|
||||
- npm test
|
||||
after_success:
|
||||
- bash <(curl -s https://codecov.io/bash)
|
||||
matrix:
|
||||
fast_finish: true
|
||||
1896
CHANGELOG.md
1896
CHANGELOG.md
File diff suppressed because it is too large
Load Diff
74
CODE_OF_CONDUCT.md
Normal file
74
CODE_OF_CONDUCT.md
Normal file
@ -0,0 +1,74 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, gender identity and expression, level of experience,
|
||||
nationality, personal appearance, race, religion, or sexual identity and
|
||||
orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at <https://github.com/http-party/node-http-proxy>. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at [http://contributor-covenant.org/version/1/4][version]
|
||||
|
||||
[homepage]: http://contributor-covenant.org
|
||||
[version]: http://contributor-covenant.org/version/1/4/
|
||||
4
LICENSE
4
LICENSE
@ -1,7 +1,7 @@
|
||||
|
||||
node-http-proxy
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires
|
||||
Copyright (c) 2010-2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -20,4 +20,4 @@
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
854
README.md
854
README.md
@ -1,68 +1,107 @@
|
||||
# node-http-proxy
|
||||
<p align="center">
|
||||
<img src="https://raw.github.com/http-party/node-http-proxy/master/doc/logo.png"/>
|
||||
</p>
|
||||
|
||||
<img src="http://i.imgur.com/8fTt9.png" />
|
||||
# node-http-proxy [](https://travis-ci.org/http-party/node-http-proxy) [](https://codecov.io/gh/http-party/node-http-proxy)
|
||||
|
||||
## Battle-hardened node.js http proxy
|
||||
`node-http-proxy` is an HTTP programmable proxying library that supports
|
||||
websockets. It is suitable for implementing components such as reverse
|
||||
proxies and load balancers.
|
||||
|
||||
### Features
|
||||
### Table of Contents
|
||||
* [Installation](#installation)
|
||||
* [Upgrading from 0.8.x ?](#upgrading-from-08x-)
|
||||
* [Core Concept](#core-concept)
|
||||
* [Use Cases](#use-cases)
|
||||
* [Setup a basic stand-alone proxy server](#setup-a-basic-stand-alone-proxy-server)
|
||||
* [Setup a stand-alone proxy server with custom server logic](#setup-a-stand-alone-proxy-server-with-custom-server-logic)
|
||||
* [Setup a stand-alone proxy server with proxy request header re-writing](#setup-a-stand-alone-proxy-server-with-proxy-request-header-re-writing)
|
||||
* [Modify a response from a proxied server](#modify-a-response-from-a-proxied-server)
|
||||
* [Setup a stand-alone proxy server with latency](#setup-a-stand-alone-proxy-server-with-latency)
|
||||
* [Using HTTPS](#using-https)
|
||||
* [Proxying WebSockets](#proxying-websockets)
|
||||
* [Options](#options)
|
||||
* [Listening for proxy events](#listening-for-proxy-events)
|
||||
* [Shutdown](#shutdown)
|
||||
* [Miscellaneous](#miscellaneous)
|
||||
* [Test](#test)
|
||||
* [ProxyTable API](#proxytable-api)
|
||||
* [Logo](#logo)
|
||||
* [Contributing and Issues](#contributing-and-issues)
|
||||
* [License](#license)
|
||||
|
||||
* Reverse proxies incoming http.ServerRequest streams
|
||||
* Can be used as a CommonJS module in node.js
|
||||
* Uses event buffering to support application latency in proxied requests
|
||||
* Reverse or Forward Proxy based on simple JSON-based configuration
|
||||
* Supports [WebSockets][1]
|
||||
* Supports [HTTPS][2]
|
||||
* Minimal request overhead and latency
|
||||
* Full suite of functional tests
|
||||
* Battled-hardened through __production usage__ @ [nodejitsu.com][0]
|
||||
* Written entirely in Javascript
|
||||
* Easy to use API
|
||||
### Installation
|
||||
|
||||
### When to use node-http-proxy
|
||||
`npm install http-proxy --save`
|
||||
|
||||
Let's suppose you were running multiple http application servers, but you only wanted to expose one machine to the internet. You could setup node-http-proxy on that one machine and then reverse-proxy the incoming http requests to locally running services which were not exposed to the outside network.
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
### Installing npm (node package manager)
|
||||
### Upgrading from 0.8.x ?
|
||||
|
||||
Click [here](UPGRADING.md)
|
||||
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
### Core Concept
|
||||
|
||||
A new proxy is created by calling `createProxyServer` and passing
|
||||
an `options` object as argument ([valid properties are available here](lib/http-proxy.js#L26-L42))
|
||||
|
||||
```javascript
|
||||
var httpProxy = require('http-proxy');
|
||||
|
||||
var proxy = httpProxy.createProxyServer(options); // See (†)
|
||||
```
|
||||
curl http://npmjs.org/install.sh | sh
|
||||
†Unless listen(..) is invoked on the object, this does not create a webserver. See below.
|
||||
|
||||
An object will be returned with four methods:
|
||||
|
||||
* web `req, res, [options]` (used for proxying regular HTTP(S) requests)
|
||||
* ws `req, socket, head, [options]` (used for proxying WS(S) requests)
|
||||
* listen `port` (a function that wraps the object in a webserver, for your convenience)
|
||||
* close `[callback]` (a function that closes the inner webserver and stops listening on given port)
|
||||
|
||||
It is then possible to proxy requests by calling these functions
|
||||
|
||||
```javascript
|
||||
http.createServer(function(req, res) {
|
||||
proxy.web(req, res, { target: 'http://mytarget.com:8080' });
|
||||
});
|
||||
```
|
||||
|
||||
### Installing node-http-proxy
|
||||
Errors can be listened on either using the Event Emitter API
|
||||
|
||||
```
|
||||
npm install http-proxy
|
||||
```javascript
|
||||
proxy.on('error', function(e) {
|
||||
...
|
||||
});
|
||||
```
|
||||
|
||||
## Using node-http-proxy
|
||||
or using the callback API
|
||||
|
||||
There are several ways to use node-http-proxy; the library is designed to be flexible so that it can be used by itself, or in conjunction with other node.js libraries / tools:
|
||||
```javascript
|
||||
proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });
|
||||
```
|
||||
|
||||
1. Standalone HTTP Proxy server
|
||||
2. Inside of another HTTP server (like Connect)
|
||||
3. In conjunction with a Proxy Routing Table
|
||||
4. As a forward-proxy with a reverse proxy
|
||||
5. From the command-line as a long running process
|
||||
6. customized with 3rd party middleware.
|
||||
When a request is proxied it follows two different pipelines ([available here](lib/http-proxy/passes))
|
||||
which apply transformations to both the `req` and `res` object.
|
||||
The first pipeline (incoming) is responsible for the creation and manipulation of the stream that connects your client to the target.
|
||||
The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data
|
||||
to the client.
|
||||
|
||||
In each of these scenarios node-http-proxy can handle any of these types of requests:
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
1. HTTP Requests (http://)
|
||||
2. HTTPS Requests (https://)
|
||||
3. WebSocket Requests (ws://)
|
||||
4. Secure WebSocket Requests (wss://)
|
||||
### Use Cases
|
||||
|
||||
See the [examples][3] for more working sample code.
|
||||
#### Setup a basic stand-alone proxy server
|
||||
|
||||
### Setup a basic stand-alone proxy server
|
||||
|
||||
``` js
|
||||
```js
|
||||
var http = require('http'),
|
||||
httpProxy = require('http-proxy');
|
||||
//
|
||||
// Create your proxy server
|
||||
// Create your proxy server and set the target in the options.
|
||||
//
|
||||
httpProxy.createServer(9000, 'localhost').listen(8000);
|
||||
httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000); // See (†)
|
||||
|
||||
//
|
||||
// Create your target server
|
||||
@ -73,362 +112,457 @@ http.createServer(function (req, res) {
|
||||
res.end();
|
||||
}).listen(9000);
|
||||
```
|
||||
†Invoking listen(..) triggers the creation of a web server. Otherwise, just the proxy instance is created.
|
||||
|
||||
### Setup a stand-alone proxy server with custom server logic
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
``` js
|
||||
#### Setup a stand-alone proxy server with custom server logic
|
||||
This example shows how you can proxy a request using your own HTTP server
|
||||
and also you can put your own logic to handle the request.
|
||||
|
||||
```js
|
||||
var http = require('http'),
|
||||
httpProxy = require('http-proxy');
|
||||
|
||||
|
||||
//
|
||||
// Create a proxy server with custom application logic
|
||||
//
|
||||
httpProxy.createServer(function (req, res, proxy) {
|
||||
//
|
||||
// Put your custom server logic here
|
||||
//
|
||||
proxy.proxyRequest(req, res, {
|
||||
host: 'localhost',
|
||||
port: 9000
|
||||
});
|
||||
}).listen(8000);
|
||||
var proxy = httpProxy.createProxyServer({});
|
||||
|
||||
http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully proxied: ' + req.url +'\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9000);
|
||||
//
|
||||
// Create your custom server and just call `proxy.web()` to proxy
|
||||
// a web request to the target passed in the options
|
||||
// also you can use `proxy.ws()` to proxy a websockets request
|
||||
//
|
||||
var server = http.createServer(function(req, res) {
|
||||
// You can define here your custom logic to handle the request
|
||||
// and then proxy the request.
|
||||
proxy.web(req, res, { target: 'http://127.0.0.1:5050' });
|
||||
});
|
||||
|
||||
console.log("listening on port 5050")
|
||||
server.listen(5050);
|
||||
```
|
||||
|
||||
### Setup a stand-alone proxy server with latency (e.g. IO, etc)
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
``` js
|
||||
#### Setup a stand-alone proxy server with proxy request header re-writing
|
||||
This example shows how you can proxy a request using your own HTTP server that
|
||||
modifies the outgoing proxy request by adding a special header.
|
||||
|
||||
```js
|
||||
var http = require('http'),
|
||||
httpProxy = require('http-proxy');
|
||||
|
||||
//
|
||||
// Create a proxy server with custom application logic
|
||||
//
|
||||
httpProxy.createServer(function (req, res, proxy) {
|
||||
//
|
||||
// Buffer the request so that `data` and `end` events
|
||||
// are not lost during async operation(s).
|
||||
//
|
||||
var buffer = httpProxy.buffer(req);
|
||||
|
||||
//
|
||||
// Wait for two seconds then respond: this simulates
|
||||
// performing async actions before proxying a request
|
||||
//
|
||||
var proxy = httpProxy.createProxyServer({});
|
||||
|
||||
// To modify the proxy connection before data is sent, you can listen
|
||||
// for the 'proxyReq' event. When the event is fired, you will receive
|
||||
// the following arguments:
|
||||
// (http.ClientRequest proxyReq, http.IncomingMessage req,
|
||||
// http.ServerResponse res, Object options). This mechanism is useful when
|
||||
// you need to modify the proxy request before the proxy connection
|
||||
// is made to the target.
|
||||
//
|
||||
proxy.on('proxyReq', function(proxyReq, req, res, options) {
|
||||
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
|
||||
});
|
||||
|
||||
var server = http.createServer(function(req, res) {
|
||||
// You can define here your custom logic to handle the request
|
||||
// and then proxy the request.
|
||||
proxy.web(req, res, {
|
||||
target: 'http://127.0.0.1:5050'
|
||||
});
|
||||
});
|
||||
|
||||
console.log("listening on port 5050")
|
||||
server.listen(5050);
|
||||
```
|
||||
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
#### Modify a response from a proxied server
|
||||
Sometimes when you have received a HTML/XML document from the server of origin you would like to modify it before forwarding it on.
|
||||
|
||||
[Harmon](https://github.com/No9/harmon) allows you to do this in a streaming style so as to keep the pressure on the proxy to a minimum.
|
||||
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
#### Setup a stand-alone proxy server with latency
|
||||
|
||||
```js
|
||||
var http = require('http'),
|
||||
httpProxy = require('http-proxy');
|
||||
|
||||
//
|
||||
// Create a proxy server with latency
|
||||
//
|
||||
var proxy = httpProxy.createProxyServer();
|
||||
|
||||
//
|
||||
// Create your server that makes an operation that waits a while
|
||||
// and then proxies the request
|
||||
//
|
||||
http.createServer(function (req, res) {
|
||||
// This simulates an operation that takes 500ms to execute
|
||||
setTimeout(function () {
|
||||
proxy.proxyRequest(req, res, {
|
||||
host: 'localhost',
|
||||
port: 9000,
|
||||
buffer: buffer
|
||||
});
|
||||
}, 2000);
|
||||
}).listen(8000);
|
||||
|
||||
http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully proxied: ' + req.url +'\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9000);
|
||||
```
|
||||
|
||||
### Proxy requests within another http server
|
||||
|
||||
``` js
|
||||
var http = require('http'),
|
||||
httpProxy = require('http-proxy');
|
||||
|
||||
//
|
||||
// Create a new instance of HttProxy to use in your server
|
||||
//
|
||||
var proxy = new httpProxy.RoutingProxy();
|
||||
|
||||
//
|
||||
// Create a regular http server and proxy its handler
|
||||
//
|
||||
http.createServer(function (req, res) {
|
||||
//
|
||||
// Put your custom server logic here, then proxy
|
||||
//
|
||||
proxy.proxyRequest(req, res, {
|
||||
host: 'localhost',
|
||||
port: 9000
|
||||
});
|
||||
}).listen(8001);
|
||||
|
||||
http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully proxied: ' + req.url +'\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9000);
|
||||
```
|
||||
|
||||
### Proxy requests using a ProxyTable
|
||||
A Proxy Table is a simple lookup table that maps incoming requests to proxy target locations. Take a look at an example of the options you need to pass to httpProxy.createServer:
|
||||
|
||||
``` js
|
||||
var options = {
|
||||
router: {
|
||||
'foo.com/baz': '127.0.0.1:8001',
|
||||
'foo.com/buz': '127.0.0.1:8002',
|
||||
'bar.com/buz': '127.0.0.1:8003'
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
The above route table will take incoming requests to 'foo.com/baz' and forward them to '127.0.0.1:8001'. Likewise it will take incoming requests to 'foo.com/buz' and forward them to '127.0.0.1:8002'. The routes themselves are later converted to regular expressions to enable more complex matching functionality. We can create a proxy server with these options by using the following code:
|
||||
|
||||
``` js
|
||||
var proxyServer = httpProxy.createServer(options);
|
||||
proxyServer.listen(80);
|
||||
```
|
||||
|
||||
### Proxy requests using a 'Hostname Only' ProxyTable
|
||||
As mentioned in the previous section, all routes passes to the ProxyTable are by default converted to regular expressions that are evaluated at proxy-time. This is good for complex URL rewriting of proxy requests, but less efficient when one simply wants to do pure hostname routing based on the HTTP 'Host' header. If you are only concerned with hostname routing, you change the lookup used by the internal ProxyTable:
|
||||
|
||||
``` js
|
||||
var options = {
|
||||
hostnameOnly: true,
|
||||
router: {
|
||||
'foo.com': '127.0.0.1:8001',
|
||||
'bar.com': '127.0.0.1:8002'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Notice here that I have not included paths on the individual domains because this is not possible when using only the HTTP 'Host' header. Care to learn more? See [RFC2616: HTTP/1.1, Section 14.23, "Host"][4].
|
||||
|
||||
### Proxy requests with an additional forward proxy
|
||||
Sometimes in addition to a reverse proxy, you may want your front-facing server to forward traffic to another location. For example, if you wanted to load test your staging environment. This is possible when using node-http-proxy using similar JSON-based configuration to a proxy table:
|
||||
|
||||
``` js
|
||||
var proxyServerWithForwarding = httpProxy.createServer(9000, 'localhost', {
|
||||
forward: {
|
||||
port: 9000,
|
||||
host: 'staging.com'
|
||||
}
|
||||
});
|
||||
proxyServerWithForwarding.listen(80);
|
||||
```
|
||||
|
||||
The forwarding option can be used in conjunction with the proxy table options by simply including both the 'forward' and 'router' properties in the options passed to 'createServer'.
|
||||
|
||||
|
||||
## Using HTTPS
|
||||
You have all the full flexibility of node-http-proxy offers in HTTPS as well as HTTP. The two basic scenarios are: with a stand-alone proxy server or in conjunction with another HTTPS server.
|
||||
|
||||
### Proxying to HTTP from HTTPS
|
||||
This is probably the most common use-case for proxying in conjunction with HTTPS. You have some front-facing HTTPS server, but all of your internal traffic is HTTP. In this way, you can reduce the number of servers to which your CA and other important security files are deployed and reduce the computational overhead from HTTPS traffic.
|
||||
|
||||
Using HTTPS in `node-http-proxy` is relatively straight-forward:
|
||||
|
||||
``` js
|
||||
var fs = require('fs'),
|
||||
http = require('http'),
|
||||
https = require('https'),
|
||||
httpProxy = require('http-proxy');
|
||||
|
||||
var options = {
|
||||
https: {
|
||||
key: fs.readFileSync('path/to/your/key.pem', 'utf8'),
|
||||
cert: fs.readFileSync('path/to/your/cert.pem', 'utf8')
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
// Create a standalone HTTPS proxy server
|
||||
//
|
||||
httpProxy.createServer(8000, 'localhost', options).listen(8001);
|
||||
|
||||
//
|
||||
// Create an instance of HttpProxy to use with another HTTPS server
|
||||
//
|
||||
var proxy = new httpProxy.HttpProxy({
|
||||
target: {
|
||||
host: 'localhost',
|
||||
port: 8000
|
||||
}
|
||||
});
|
||||
https.createServer(options.https, function (req, res) {
|
||||
proxy.proxyRequest(req, res)
|
||||
}).listen(8002);
|
||||
|
||||
//
|
||||
// Create the target HTTPS server for both cases
|
||||
//
|
||||
http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('hello https\n');
|
||||
res.end();
|
||||
}).listen(8000);
|
||||
```
|
||||
|
||||
### Proxying to HTTPS from HTTPS
|
||||
Proxying from HTTPS to HTTPS is essentially the same as proxying from HTTPS to HTTP, but you must include the `target` option in when calling `httpProxy.createServer` or instantiating a new instance of `HttpProxy`.
|
||||
|
||||
``` js
|
||||
var fs = require('fs'),
|
||||
https = require('https'),
|
||||
httpProxy = require('http-proxy');
|
||||
|
||||
var options = {
|
||||
https: {
|
||||
key: fs.readFileSync('path/to/your/key.pem', 'utf8'),
|
||||
cert: fs.readFileSync('path/to/your/cert.pem', 'utf8')
|
||||
},
|
||||
target: {
|
||||
https: true // This could also be an Object with key and cert properties
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
// Create a standalone HTTPS proxy server
|
||||
//
|
||||
httpProxy.createServer(8000, 'localhost', options).listen(8001);
|
||||
|
||||
//
|
||||
// Create an instance of HttpProxy to use with another HTTPS server
|
||||
//
|
||||
var proxy = new httpProxy.HttpProxy({
|
||||
target: {
|
||||
host: 'localhost',
|
||||
port: 8000,
|
||||
https: true
|
||||
}
|
||||
});
|
||||
|
||||
https.createServer(options.https, function (req, res) {
|
||||
proxy.proxyRequest(req, res);
|
||||
}).listen(8002);
|
||||
|
||||
//
|
||||
// Create the target HTTPS server for both cases
|
||||
//
|
||||
https.createServer(options.https, function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('hello https\n');
|
||||
res.end();
|
||||
}).listen(8000);
|
||||
```
|
||||
## Middleware
|
||||
|
||||
`node-http-proxy` now supports connect middleware. Add middleware functions to your createServer call:
|
||||
|
||||
``` js
|
||||
httpProxy.createServer(
|
||||
require('connect-gzip').gzip(),
|
||||
9000, 'localhost'
|
||||
).listen(8000);
|
||||
```
|
||||
|
||||
## Proxying WebSockets
|
||||
Websockets are handled automatically when using `httpProxy.createServer()`, but if you want to use it in conjunction with a stand-alone HTTP + WebSocket (such as [socket.io][5]) server here's how:
|
||||
|
||||
``` js
|
||||
var http = require('http'),
|
||||
httpProxy = require('http-proxy');
|
||||
|
||||
//
|
||||
// Create an instance of node-http-proxy
|
||||
//
|
||||
var proxy = new httpProxy.HttpProxy(
|
||||
target: {
|
||||
host: 'localhost',
|
||||
port: 8000
|
||||
proxy.web(req, res, {
|
||||
target: 'http://localhost:9008'
|
||||
});
|
||||
}, 500);
|
||||
}).listen(8008);
|
||||
|
||||
var server = http.createServer(function (req, res) {
|
||||
//
|
||||
// Proxy normal HTTP requests
|
||||
//
|
||||
proxy.proxyRequest(req, res);
|
||||
//
|
||||
// Create your target server
|
||||
//
|
||||
http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9008);
|
||||
```
|
||||
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
#### Using HTTPS
|
||||
You can activate the validation of a secure SSL certificate to the target connection (avoid self-signed certs), just set `secure: true` in the options.
|
||||
|
||||
##### HTTPS -> HTTP
|
||||
|
||||
```js
|
||||
//
|
||||
// Create the HTTPS proxy server in front of a HTTP server
|
||||
//
|
||||
httpProxy.createServer({
|
||||
target: {
|
||||
host: 'localhost',
|
||||
port: 9009
|
||||
},
|
||||
ssl: {
|
||||
key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
|
||||
cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
|
||||
}
|
||||
}).listen(8009);
|
||||
```
|
||||
|
||||
##### HTTPS -> HTTPS
|
||||
|
||||
```js
|
||||
//
|
||||
// Create the proxy server listening on port 443
|
||||
//
|
||||
httpProxy.createServer({
|
||||
ssl: {
|
||||
key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
|
||||
cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
|
||||
},
|
||||
target: 'https://localhost:9010',
|
||||
secure: true // Depends on your needs, could be false.
|
||||
}).listen(443);
|
||||
```
|
||||
|
||||
##### HTTP -> HTTPS (using a PKCS12 client certificate)
|
||||
|
||||
```js
|
||||
//
|
||||
// Create an HTTP proxy server with an HTTPS target
|
||||
//
|
||||
httpProxy.createProxyServer({
|
||||
target: {
|
||||
protocol: 'https:',
|
||||
host: 'my-domain-name',
|
||||
port: 443,
|
||||
pfx: fs.readFileSync('path/to/certificate.p12'),
|
||||
passphrase: 'password',
|
||||
},
|
||||
changeOrigin: true,
|
||||
}).listen(8000);
|
||||
```
|
||||
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
#### Proxying WebSockets
|
||||
You can activate the websocket support for the proxy using `ws:true` in the options.
|
||||
|
||||
```js
|
||||
//
|
||||
// Create a proxy server for websockets
|
||||
//
|
||||
httpProxy.createServer({
|
||||
target: 'ws://localhost:9014',
|
||||
ws: true
|
||||
}).listen(8014);
|
||||
```
|
||||
|
||||
Also you can proxy the websocket requests just calling the `ws(req, socket, head)` method.
|
||||
|
||||
```js
|
||||
//
|
||||
// Setup our server to proxy standard HTTP requests
|
||||
//
|
||||
var proxy = new httpProxy.createProxyServer({
|
||||
target: {
|
||||
host: 'localhost',
|
||||
port: 9015
|
||||
}
|
||||
});
|
||||
var proxyServer = http.createServer(function (req, res) {
|
||||
proxy.web(req, res);
|
||||
});
|
||||
|
||||
server.on('upgrade', function(req, socket, head) {
|
||||
//
|
||||
// Proxy websocket requests too
|
||||
//
|
||||
proxy.proxyWebSocketRequest(req, socket, head);
|
||||
//
|
||||
// Listen to the `upgrade` event and proxy the
|
||||
// WebSocket requests as well.
|
||||
//
|
||||
proxyServer.on('upgrade', function (req, socket, head) {
|
||||
proxy.ws(req, socket, head);
|
||||
});
|
||||
|
||||
proxyServer.listen(8015);
|
||||
```
|
||||
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
### Options
|
||||
|
||||
`httpProxy.createProxyServer` supports the following options:
|
||||
|
||||
* **target**: url string to be parsed with the url module
|
||||
* **forward**: url string to be parsed with the url module
|
||||
* **agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects)
|
||||
* **ssl**: object to be passed to https.createServer()
|
||||
* **ws**: true/false, if you want to proxy websockets
|
||||
* **xfwd**: true/false, adds x-forward headers
|
||||
* **secure**: true/false, if you want to verify the SSL Certs
|
||||
* **toProxy**: true/false, passes the absolute URL as the `path` (useful for proxying to proxies)
|
||||
* **prependPath**: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path
|
||||
* **ignorePath**: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required).
|
||||
* **localAddress**: Local interface string to bind for outgoing connections
|
||||
* **changeOrigin**: true/false, Default: false - changes the origin of the host header to the target URL
|
||||
* **preserveHeaderKeyCase**: true/false, Default: false - specify whether you want to keep letter case of response header key
|
||||
* **auth**: Basic authentication i.e. 'user:password' to compute an Authorization header.
|
||||
* **hostRewrite**: rewrites the location hostname on (201/301/302/307/308) redirects.
|
||||
* **autoRewrite**: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
|
||||
* **protocolRewrite**: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
|
||||
* **cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values:
|
||||
* `false` (default): disable cookie rewriting
|
||||
* String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`.
|
||||
* Object: mapping of domains to new domains, use `"*"` to match all domains.
|
||||
For example keep one domain unchanged, rewrite one domain and remove other domains:
|
||||
```
|
||||
cookieDomainRewrite: {
|
||||
"unchanged.domain": "unchanged.domain",
|
||||
"old.domain": "new.domain",
|
||||
"*": ""
|
||||
}
|
||||
```
|
||||
* **cookiePathRewrite**: rewrites path of `set-cookie` headers. Possible values:
|
||||
* `false` (default): disable cookie rewriting
|
||||
* String: new path, for example `cookiePathRewrite: "/newPath/"`. To remove the path, use `cookiePathRewrite: ""`. To set path to root use `cookiePathRewrite: "/"`.
|
||||
* Object: mapping of paths to new paths, use `"*"` to match all paths.
|
||||
For example, to keep one path unchanged, rewrite one path and remove other paths:
|
||||
```
|
||||
cookiePathRewrite: {
|
||||
"/unchanged.path/": "/unchanged.path/",
|
||||
"/old.path/": "/new.path/",
|
||||
"*": ""
|
||||
}
|
||||
```
|
||||
* **headers**: object with extra headers to be added to target requests.
|
||||
* **proxyTimeout**: timeout (in millis) for outgoing proxy requests
|
||||
* **timeout**: timeout (in millis) for incoming requests
|
||||
* **followRedirects**: true/false, Default: false - specify whether you want to follow redirects
|
||||
* **selfHandleResponse** true/false, if set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the `proxyRes` event
|
||||
* **buffer**: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e.g. If you read the body of a request into a field called 'req.rawbody' you could restream this field in the buffer option:
|
||||
|
||||
```
|
||||
'use strict';
|
||||
|
||||
const streamify = require('stream-array');
|
||||
const HttpProxy = require('http-proxy');
|
||||
const proxy = new HttpProxy();
|
||||
|
||||
module.exports = (req, res, next) => {
|
||||
|
||||
proxy.web(req, res, {
|
||||
target: 'http://localhost:4003/',
|
||||
buffer: streamify(req.rawBody)
|
||||
}, next);
|
||||
|
||||
};
|
||||
```
|
||||
|
||||
**NOTE:**
|
||||
`options.ws` and `options.ssl` are optional.
|
||||
`options.target` and `options.forward` cannot both be missing
|
||||
|
||||
If you are using the `proxyServer.listen` method, the following options are also applicable:
|
||||
|
||||
* **ssl**: object to be passed to https.createServer()
|
||||
* **ws**: true/false, if you want to proxy websockets
|
||||
|
||||
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
### Listening for proxy events
|
||||
|
||||
* `error`: The error event is emitted if the request to the target fail. **We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.**
|
||||
* `proxyReq`: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "web" connections
|
||||
* `proxyReqWs`: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "websocket" connections
|
||||
* `proxyRes`: This event is emitted if the request to the target got a response.
|
||||
* `open`: This event is emitted once the proxy websocket was created and piped into the target websocket.
|
||||
* `close`: This event is emitted once the proxy websocket was closed.
|
||||
* (DEPRECATED) `proxySocket`: Deprecated in favor of `open`.
|
||||
|
||||
```js
|
||||
var httpProxy = require('http-proxy');
|
||||
// Error example
|
||||
//
|
||||
// Http Proxy Server with bad target
|
||||
//
|
||||
var proxy = httpProxy.createServer({
|
||||
target:'http://localhost:9005'
|
||||
});
|
||||
|
||||
proxy.listen(8005);
|
||||
|
||||
//
|
||||
// Listen for the `error` event on `proxy`.
|
||||
proxy.on('error', function (err, req, res) {
|
||||
res.writeHead(500, {
|
||||
'Content-Type': 'text/plain'
|
||||
});
|
||||
|
||||
res.end('Something went wrong. And we are reporting a custom error message.');
|
||||
});
|
||||
|
||||
//
|
||||
// Listen for the `proxyRes` event on `proxy`.
|
||||
//
|
||||
proxy.on('proxyRes', function (proxyRes, req, res) {
|
||||
console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
|
||||
});
|
||||
|
||||
//
|
||||
// Listen for the `open` event on `proxy`.
|
||||
//
|
||||
proxy.on('open', function (proxySocket) {
|
||||
// listen for messages coming FROM the target here
|
||||
proxySocket.on('data', hybiParseAndLogMessage);
|
||||
});
|
||||
|
||||
//
|
||||
// Listen for the `close` event on `proxy`.
|
||||
//
|
||||
proxy.on('close', function (res, socket, head) {
|
||||
// view disconnected websocket connections
|
||||
console.log('Client disconnected');
|
||||
});
|
||||
```
|
||||
|
||||
### Configuring your Socket limits
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
By default, `node-http-proxy` will set a 100 socket limit for all `host:port` proxy targets. If you wish to change this you can two it in two ways:
|
||||
### Shutdown
|
||||
|
||||
1. By passing the `maxSockets` option to `httpProxy.createServer()`
|
||||
2. By calling `httpProxy.setMaxSockets(n)`, where `n` is the number of sockets you with to use.
|
||||
* When testing or running server within another program it may be necessary to close the proxy.
|
||||
* This will stop the proxy from accepting new connections.
|
||||
|
||||
## Using node-http-proxy from the command line
|
||||
When you install this package with npm, a node-http-proxy binary will become available to you. Using this binary is easy with some simple options:
|
||||
```js
|
||||
var proxy = new httpProxy.createProxyServer({
|
||||
target: {
|
||||
host: 'localhost',
|
||||
port: 1337
|
||||
}
|
||||
});
|
||||
|
||||
``` js
|
||||
usage: node-http-proxy [options]
|
||||
|
||||
All options should be set with the syntax --option=value
|
||||
|
||||
options:
|
||||
--port PORT Port that the proxy server should run on
|
||||
--target HOST:PORT Location of the server the proxy will target
|
||||
--config OUTFILE Location of the configuration file for the proxy server
|
||||
--silent Silence the log output from the proxy server
|
||||
-h, --help You're staring at it
|
||||
proxy.close();
|
||||
```
|
||||
|
||||
<br/>
|
||||
## Why doesn't node-http-proxy have more advanced features like x, y, or z?
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
If you have a suggestion for a feature currently not supported, feel free to open a [support issue][6]. node-http-proxy is designed to just proxy http requests from one server to another, but we will be soon releasing many other complimentary projects that can be used in conjunction with node-http-proxy.
|
||||
### Miscellaneous
|
||||
|
||||
## Run Tests
|
||||
The test suite is designed to fully cover the combinatoric possibilities of HTTP and HTTPS proxying:
|
||||
If you want to handle your own response after receiving the `proxyRes`, you can do
|
||||
so with `selfHandleResponse`. As you can see below, if you use this option, you
|
||||
are able to intercept and read the `proxyRes` but you must also make sure to
|
||||
reply to the `res` itself otherwise the original client will never receive any
|
||||
data.
|
||||
|
||||
### Modify response
|
||||
|
||||
```js
|
||||
|
||||
var option = {
|
||||
target: target,
|
||||
selfHandleResponse : true
|
||||
};
|
||||
proxy.on('proxyRes', function (proxyRes, req, res) {
|
||||
var body = [];
|
||||
proxyRes.on('data', function (chunk) {
|
||||
body.push(chunk);
|
||||
});
|
||||
proxyRes.on('end', function () {
|
||||
body = Buffer.concat(body).toString();
|
||||
console.log("res from proxied server:", body);
|
||||
res.end("my response to cli");
|
||||
});
|
||||
});
|
||||
proxy.web(req, res, option);
|
||||
|
||||
1. HTTP --> HTTP
|
||||
2. HTTPS --> HTTP
|
||||
3. HTTPS --> HTTPS
|
||||
4. HTTP --> HTTPS
|
||||
|
||||
```
|
||||
vows test/*-test.js --spec
|
||||
vows test/*-test.js --spec --https
|
||||
vows test/*-test.js --spec --https --target=https
|
||||
vows test/*-test.js --spec --target=https
|
||||
|
||||
#### ProxyTable API
|
||||
|
||||
A proxy table API is available through this add-on [module](https://github.com/donasaur/http-proxy-rules), which lets you define a set of rules to translate matching routes to target routes that the reverse proxy will talk to.
|
||||
|
||||
#### Test
|
||||
|
||||
```
|
||||
$ npm test
|
||||
```
|
||||
|
||||
<br/>
|
||||
#### Logo
|
||||
|
||||
Logo created by [Diego Pasquali](http://dribbble.com/diegopq)
|
||||
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
### Contributing and Issues
|
||||
|
||||
* Read carefully our [Code Of Conduct](https://github.com/http-party/node-http-proxy/blob/master/CODE_OF_CONDUCT.md)
|
||||
* Search on Google/Github
|
||||
* If you can't find anything, open an issue
|
||||
* If you feel comfortable about fixing the issue, fork the repo
|
||||
* Commit to your local branch (which must be different from `master`)
|
||||
* Submit your Pull Request (be sure to include tests and update documentation)
|
||||
|
||||
**[Back to top](#table-of-contents)**
|
||||
|
||||
### License
|
||||
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
[0]: http://nodejitsu.com
|
||||
[1]: https://github.com/nodejitsu/node-http-proxy/blob/master/examples/web-socket-proxy.js
|
||||
[2]: https://github.com/nodejitsu/node-http-proxy/blob/master/examples/basic-proxy-https.js
|
||||
[3]: https://github.com/nodejitsu/node-http-proxy/tree/v0.5.0/examples
|
||||
[4]: http://www.ietf.org/rfc/rfc2616.txt
|
||||
[5]: http://socket.io
|
||||
[6]: http://github.com/nodejitsu/node-http-proxy/issues
|
||||
>The MIT License (MIT)
|
||||
>
|
||||
>Copyright (c) 2010 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
>
|
||||
>Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
>of this software and associated documentation files (the "Software"), to deal
|
||||
>in the Software without restriction, including without limitation the rights
|
||||
>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
>copies of the Software, and to permit persons to whom the Software is
|
||||
>furnished to do so, subject to the following conditions:
|
||||
>
|
||||
>The above copyright notice and this permission notice shall be included in
|
||||
>all copies or substantial portions of the Software.
|
||||
>
|
||||
>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
>AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
>LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
>OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
>THE SOFTWARE.
|
||||
|
||||
97
UPGRADING.md
Normal file
97
UPGRADING.md
Normal file
@ -0,0 +1,97 @@
|
||||
Looking to upgrade from `http-proxy@0.x.x` to `http-proxy@1.0`? You've come to the right place!
|
||||
`http-proxy@1.0` is a from-scratch implementation of `http-proxy` and, as such
|
||||
brings some breaking changes to APIs.
|
||||
|
||||
## Server creation
|
||||
|
||||
Available through `.createServer()` or `.createProxyServer()`.
|
||||
|
||||
```javascript
|
||||
httpProxy.createServer({
|
||||
target:'http://localhost:9003'
|
||||
}).listen(8003);
|
||||
```
|
||||
|
||||
Check the [README.md](https://github.com/http-party/node-http-proxy/blob/caronte/README.md) for a more detailed explanation of the parameters.
|
||||
|
||||
## Proxying
|
||||
|
||||
Web proxying is done by calling the `.web()` method on a Proxy instance. You can check among some use cases in the [examples folder](https://github.com/http-party/node-http-proxy/tree/caronte/examples/http)
|
||||
|
||||
```javascript
|
||||
//
|
||||
// Create a HTTP Proxy server with a HTTPS target
|
||||
//
|
||||
httpProxy.createProxyServer({
|
||||
target: 'https://google.com',
|
||||
agent : https.globalAgent,
|
||||
headers: {
|
||||
host: 'google.com'
|
||||
}
|
||||
}).listen(8011);
|
||||
|
||||
```
|
||||
|
||||
Websockets are proxied by the `.ws()` method. The [examples folder](https://github.com/http-party/node-http-proxy/tree/caronte/examples/websocket) again provides a lot of useful snippets!
|
||||
|
||||
```javascript
|
||||
var proxy = new httpProxy.createProxyServer({
|
||||
target: {
|
||||
host: 'localhost',
|
||||
port: 9015
|
||||
}
|
||||
});
|
||||
var proxyServer = http.createServer(function (req, res) {
|
||||
proxy.web(req, res);
|
||||
});
|
||||
|
||||
//
|
||||
// Listen to the `upgrade` event and proxy the
|
||||
// WebSocket requests as well.
|
||||
//
|
||||
proxyServer.on('upgrade', function (req, socket, head) {
|
||||
proxy.ws(req, socket, head);
|
||||
});
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
It is possible to listen globally on the `error` event on the server. In alternative, a
|
||||
callback passed to `.web()` or `.ws()` as last parameter is also accepted.
|
||||
|
||||
```javascript
|
||||
var proxy = httpProxy.createServer({
|
||||
target:'http://localhost:9005'
|
||||
});
|
||||
|
||||
//
|
||||
// Tell the proxy to listen on port 8000
|
||||
//
|
||||
proxy.listen(8005);
|
||||
|
||||
//
|
||||
// Listen for the `error` event on `proxy`.
|
||||
proxy.on('error', function (err, req, res) {
|
||||
res.writeHead(500, {
|
||||
'Content-Type': 'text/plain'
|
||||
});
|
||||
|
||||
res.end('Something went wrong. And we are reporting a custom error message.');
|
||||
});
|
||||
```
|
||||
|
||||
## Dropped
|
||||
|
||||
Since the API was rewritten to be extremely flexible we decided to drop some features
|
||||
which were in the core and delegate them to eventual "userland" modules.
|
||||
|
||||
- Middleware API
|
||||
- ProxyTable API
|
||||
|
||||
### Middleware API
|
||||
|
||||
The new API makes it really easy to implement code that behaves like the old Middleware API. You can check some examples [here](https://github.com/http-party/node-http-proxy/tree/caronte/examples/middleware)
|
||||
|
||||
### ProxyTable API
|
||||
|
||||
See this [link](https://github.com/donasaur/http-proxy-rules/) for an add-on proxy rules module that you can use to simulate the old ProxyTable API.
|
||||
37
benchmark/README.md
Normal file
37
benchmark/README.md
Normal file
@ -0,0 +1,37 @@
|
||||
# Benchmarking `node-http-proxy`
|
||||
|
||||
The long-term goal of these scripts and documentation is to provide a consistent and well understood benchmarking process for `node-http-proxy` so that performance does not degrade over time. They were initially created to compare the performance of `v0.10.3` and `v1.0.0` (which was a significant rewrite).
|
||||
|
||||
## Pre-requisites
|
||||
|
||||
All benchmarking shall be done with [wrk](https://github.com/wg/wrk) which _is the same tool used for performance testing by the node.js core team._ **Make sure you have `wrk` installed before continuing**.
|
||||
|
||||
```
|
||||
$ wrk
|
||||
Usage: wrk <options> <url>
|
||||
Options:
|
||||
-c, --connections <N> Connections to keep open
|
||||
-d, --duration <T> Duration of test
|
||||
-t, --threads <N> Number of threads to use
|
||||
|
||||
-s, --script <S> Load Lua script file
|
||||
-H, --header <H> Add header to request
|
||||
--latency Print latency statistics
|
||||
--timeout <T> Socket/request timeout
|
||||
-v, --version Print version details
|
||||
|
||||
Numeric arguments may include a SI unit (1k, 1M, 1G)
|
||||
Time arguments may include a time unit (2s, 2m, 2h)
|
||||
```
|
||||
|
||||
## Benchmarks
|
||||
|
||||
1. [Simple HTTP benchmark](#simple-http)
|
||||
|
||||
### Simple HTTP
|
||||
|
||||
_This benchmark requires three terminals running:_
|
||||
|
||||
1. **A proxy server:** `node benchmark/scripts/proxy.js`
|
||||
2. **A target server:** `node benchmark/scripts/hello.js`
|
||||
3. **A wrk process:** `wrk -c 20 -d5m -t 2 http://127.0.0.1:8000`
|
||||
3
benchmark/scripts/hello.js
Normal file
3
benchmark/scripts/hello.js
Normal file
@ -0,0 +1,3 @@
|
||||
require('http').createServer(function(req, res) {
|
||||
res.end('Hello world!');
|
||||
}).listen(9000);
|
||||
6
benchmark/scripts/proxy.js
Normal file
6
benchmark/scripts/proxy.js
Normal file
@ -0,0 +1,6 @@
|
||||
var http = require('http'),
|
||||
httpProxy = require('../../');
|
||||
//
|
||||
// Create your proxy server
|
||||
//
|
||||
httpProxy.createProxyServer({ target: 'http://localhost:9000' }).listen(8000);
|
||||
88
benchmark/scripts/websockets-throughput.js
Normal file
88
benchmark/scripts/websockets-throughput.js
Normal file
@ -0,0 +1,88 @@
|
||||
var crypto = require('crypto'),
|
||||
WebSocket = require('ws'),
|
||||
async = require('async'),
|
||||
httpProxy = require('../../');
|
||||
|
||||
var SERVER_PORT = 8415,
|
||||
PROXY_PORT = 8514;
|
||||
|
||||
var testSets = [
|
||||
{
|
||||
size: 1024 * 1024, // 1 MB
|
||||
count: 128 // 128 MB
|
||||
},
|
||||
{
|
||||
size: 1024, // 1 KB,
|
||||
count: 1024 // 1 MB
|
||||
},
|
||||
{
|
||||
size: 128, // 128 B
|
||||
count: 1024 * 8 // 1 MB
|
||||
}
|
||||
];
|
||||
|
||||
testSets.forEach(function (set) {
|
||||
set.buffer = new Buffer(crypto.randomBytes(set.size));
|
||||
|
||||
set.buffers = [];
|
||||
for (var i = 0; i < set.count; i++) {
|
||||
set.buffers.push(set.buffer);
|
||||
}
|
||||
});
|
||||
|
||||
function runSet(set, callback) {
|
||||
function runAgainst(port, callback) {
|
||||
function send(sock) {
|
||||
sock.send(set.buffers[got++]);
|
||||
if (got === set.count) {
|
||||
t = new Date() - t;
|
||||
|
||||
server.close();
|
||||
proxy.close();
|
||||
|
||||
callback(null, t);
|
||||
}
|
||||
}
|
||||
|
||||
var server = new WebSocket.Server({ port: SERVER_PORT }),
|
||||
proxy = httpProxy.createServer(SERVER_PORT, 'localhost').listen(PROXY_PORT),
|
||||
client = new WebSocket('ws://localhost:' + port),
|
||||
got = 0,
|
||||
t = new Date();
|
||||
|
||||
server.on('connection', function (ws) {
|
||||
send(ws);
|
||||
|
||||
ws.on('message', function (msg) {
|
||||
send(ws);
|
||||
});
|
||||
});
|
||||
|
||||
client.on('message', function () {
|
||||
send(client);
|
||||
});
|
||||
}
|
||||
|
||||
async.series({
|
||||
server: async.apply(runAgainst, SERVER_PORT),
|
||||
proxy: async.apply(runAgainst, PROXY_PORT)
|
||||
}, function (err, results) {
|
||||
if (err) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
var mb = (set.size * set.count) / (1024 * 1024);
|
||||
console.log(set.size / (1024) + ' KB * ' + set.count + ' (' + mb + ' MB)');
|
||||
|
||||
Object.keys(results).forEach(function (key) {
|
||||
var t = results[key],
|
||||
throughput = mb / (t / 1000);
|
||||
|
||||
console.log(' ' + key + ' took ' + t + ' ms (' + throughput + ' MB/s)');
|
||||
});
|
||||
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
async.forEachLimit(testSets, 1, runSet);
|
||||
@ -1,3 +0,0 @@
|
||||
Benchmarks are being run on a development laptop using apache ab (everything running locally, on one machine)
|
||||
|
||||
These benchmarks should not be considered very accurate, or indicative of actual results. There are numerous factors that could cause these numbers to be inaccurate. These benchmarks should only be considered a very basic baseline to determine changes in performance as we iterate on this project.
|
||||
@ -1,56 +0,0 @@
|
||||
$ ab -c 50 -n 1000 -k http://127.0.0.1:9000/
|
||||
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
|
||||
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
|
||||
Licensed to The Apache Software Foundation, http://www.apache.org/
|
||||
|
||||
Benchmarking 127.0.0.1 (be patient)
|
||||
Completed 100 requests
|
||||
Completed 200 requests
|
||||
Completed 300 requests
|
||||
Completed 400 requests
|
||||
Completed 500 requests
|
||||
Completed 600 requests
|
||||
Completed 700 requests
|
||||
Completed 800 requests
|
||||
Completed 900 requests
|
||||
Completed 1000 requests
|
||||
Finished 1000 requests
|
||||
|
||||
|
||||
Server Software:
|
||||
Server Hostname: 127.0.0.1
|
||||
Server Port: 9000
|
||||
|
||||
Document Path: /
|
||||
Document Length: 149 bytes
|
||||
|
||||
Concurrency Level: 50
|
||||
Time taken for tests: 0.178 seconds
|
||||
Complete requests: 1000
|
||||
Failed requests: 0
|
||||
Write errors: 0
|
||||
Keep-Alive requests: 0
|
||||
Total transferred: 213213 bytes
|
||||
HTML transferred: 149149 bytes
|
||||
Requests per second: 5627.84 [#/sec] (mean)
|
||||
Time per request: 8.884 [ms] (mean)
|
||||
Time per request: 0.178 [ms] (mean, across all concurrent requests)
|
||||
Transfer rate: 1171.81 [Kbytes/sec] received
|
||||
|
||||
Connection Times (ms)
|
||||
min mean[+/-sd] median max
|
||||
Connect: 0 1 0.9 1 5
|
||||
Processing: 3 8 2.6 7 17
|
||||
Waiting: 1 7 2.4 7 17
|
||||
Total: 5 9 2.4 8 17
|
||||
|
||||
Percentage of the requests served within a certain time (ms)
|
||||
50% 8
|
||||
66% 9
|
||||
75% 9
|
||||
80% 10
|
||||
90% 13
|
||||
95% 14
|
||||
98% 15
|
||||
99% 16
|
||||
100% 17 (longest request)
|
||||
@ -1,56 +0,0 @@
|
||||
$ ab -c 5 -n 1000 http://127.0.0.1:8000/
|
||||
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
|
||||
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
|
||||
Licensed to The Apache Software Foundation, http://www.apache.org/
|
||||
|
||||
Benchmarking 127.0.0.1 (be patient)
|
||||
Completed 100 requests
|
||||
Completed 200 requests
|
||||
Completed 300 requests
|
||||
Completed 400 requests
|
||||
Completed 500 requests
|
||||
Completed 600 requests
|
||||
Completed 700 requests
|
||||
Completed 800 requests
|
||||
Completed 900 requests
|
||||
Completed 1000 requests
|
||||
Finished 1000 requests
|
||||
|
||||
|
||||
Server Software:
|
||||
Server Hostname: 127.0.0.1
|
||||
Server Port: 8000
|
||||
|
||||
Document Path: /
|
||||
Document Length: 160 bytes
|
||||
|
||||
Concurrency Level: 5
|
||||
Time taken for tests: 0.450 seconds
|
||||
Complete requests: 1000
|
||||
Failed requests: 1
|
||||
(Connect: 0, Receive: 0, Length: 1, Exceptions: 0)
|
||||
Write errors: 0
|
||||
Total transferred: 252006 bytes
|
||||
HTML transferred: 160006 bytes
|
||||
Requests per second: 2219.97 [#/sec] (mean)
|
||||
Time per request: 2.252 [ms] (mean)
|
||||
Time per request: 0.450 [ms] (mean, across all concurrent requests)
|
||||
Transfer rate: 546.33 [Kbytes/sec] received
|
||||
|
||||
Connection Times (ms)
|
||||
min mean[+/-sd] median max
|
||||
Connect: 0 0 0.0 0 0
|
||||
Processing: 1 2 0.9 2 10
|
||||
Waiting: 1 2 0.9 2 10
|
||||
Total: 1 2 0.9 2 10
|
||||
|
||||
Percentage of the requests served within a certain time (ms)
|
||||
50% 2
|
||||
66% 2
|
||||
75% 3
|
||||
80% 3
|
||||
90% 3
|
||||
95% 3
|
||||
98% 3
|
||||
99% 7
|
||||
100% 10 (longest request)
|
||||
@ -1,87 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
var path = require('path'),
|
||||
fs = require('fs'),
|
||||
util = require('util'),
|
||||
argv = require('optimist').argv,
|
||||
httpProxy = require('../lib/node-http-proxy');
|
||||
|
||||
var help = [
|
||||
"usage: node-http-proxy [options] ",
|
||||
"",
|
||||
"Starts a node-http-proxy server using the specified command-line options",
|
||||
"",
|
||||
"options:",
|
||||
" --port PORT Port that the proxy server should run on",
|
||||
" --target HOST:PORT Location of the server the proxy will target",
|
||||
" --config OUTFILE Location of the configuration file for the proxy server",
|
||||
" --silent Silence the log output from the proxy server",
|
||||
" -h, --help You're staring at it"
|
||||
].join('\n');
|
||||
|
||||
if (argv.h || argv.help || Object.keys(argv).length === 2) {
|
||||
return util.puts(help);
|
||||
}
|
||||
|
||||
var location, config = {},
|
||||
port = argv.port || 80,
|
||||
target = argv.target;
|
||||
|
||||
//
|
||||
// If we were passed a config, parse it
|
||||
//
|
||||
if (argv.config) {
|
||||
try {
|
||||
var data = fs.readFileSync(argv.config);
|
||||
config = JSON.parse(data.toString());
|
||||
} catch (ex) {
|
||||
util.puts('Error starting node-http-proxy: ' + ex);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// If `config.https` is set, then load those files into the config options.
|
||||
//
|
||||
if (config.https) {
|
||||
Object.keys(config.https).forEach(function (key) {
|
||||
config.https[key] = fs.readFileSync(config.https[key], 'utf8');
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Check to see if we should silence the logs
|
||||
//
|
||||
config.silent = typeof argv.silent !== 'undefined' ? argv.silent : config.silent;
|
||||
|
||||
//
|
||||
// If we were passed a target, parse the url string
|
||||
//
|
||||
if (typeof target === 'string') location = target.split(':');
|
||||
|
||||
//
|
||||
// Create the server with the specified options
|
||||
//
|
||||
var server;
|
||||
if (location) {
|
||||
var targetPort = location.length === 1 ? 80 : parseInt(location[1]);
|
||||
server = httpProxy.createServer(targetPort, location[0], config);
|
||||
}
|
||||
else if (config.router) {
|
||||
server = httpProxy.createServer(config);
|
||||
}
|
||||
else {
|
||||
return util.puts(help);
|
||||
}
|
||||
|
||||
//
|
||||
// Start the server
|
||||
//
|
||||
server.listen(port);
|
||||
|
||||
//
|
||||
// Notify that the server is started
|
||||
//
|
||||
if (!config.silent) {
|
||||
util.puts('node-http-proxy server now listening on port: ' + port);
|
||||
}
|
||||
10
codecov.yml
Normal file
10
codecov.yml
Normal file
@ -0,0 +1,10 @@
|
||||
coverage:
|
||||
parsers:
|
||||
javascript:
|
||||
enable_partials: yes
|
||||
status:
|
||||
project:
|
||||
default:
|
||||
target: "70%"
|
||||
patch:
|
||||
enabled: false
|
||||
@ -1,10 +0,0 @@
|
||||
{
|
||||
"silent": false,
|
||||
"router": {
|
||||
"localhost": "localhost:9000"
|
||||
},
|
||||
"forward": {
|
||||
"port": 9001,
|
||||
"host": "localhost"
|
||||
}
|
||||
}
|
||||
BIN
doc/logo.png
Normal file
BIN
doc/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 46 KiB |
@ -1,90 +0,0 @@
|
||||
<!DOCTYPE html> <html> <head> <title>balancing-proxy.js</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" media="all" href="docco.css" /> </head> <body> <div id="container"> <div id="background"></div> <div id="jump_to"> Jump To … <div id="jump_wrapper"> <div id="jump_page"> <a class="source" href="balancing-proxy.html"> balancing-proxy.html </a> <a class="source" href="node-http-proxy.html"> node-http-proxy.html </a> <a class="source" href="proxy-table.html"> proxy-table.html </a> </div> </div> </div> <table cellpadding="0" cellspacing="0"> <thead> <tr> <th class="docs"> <h1> balancing-proxy.js </h1> </th> <th class="code"> </th> </tr> </thead> <tbody> <tr id="section-1"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-1">¶</a> </div> </td> <td class="code"> <div class="highlight"><pre><span class="cm">/*</span>
|
||||
<span class="cm"> balancing-proxy.js: Transparent Load-Balancing Optimized HTTP Proxy </span>
|
||||
|
||||
<span class="cm"> Copyright (c) 2011 Charlie Robbins </span>
|
||||
|
||||
<span class="cm"> Permission is hereby granted, free of charge, to any person obtaining</span>
|
||||
<span class="cm"> a copy of this software and associated documentation files (the</span>
|
||||
<span class="cm"> "Software"), to deal in the Software without restriction, including</span>
|
||||
<span class="cm"> without limitation the rights to use, copy, modify, merge, publish,</span>
|
||||
<span class="cm"> distribute, sublicense, and/or sell copies of the Software, and to</span>
|
||||
<span class="cm"> permit persons to whom the Software is furnished to do so, subject to</span>
|
||||
<span class="cm"> the following conditions:</span>
|
||||
|
||||
<span class="cm"> The above copyright notice and this permission notice shall be</span>
|
||||
<span class="cm"> included in all copies or substantial portions of the Software.</span>
|
||||
|
||||
<span class="cm"> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,</span>
|
||||
<span class="cm"> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF</span>
|
||||
<span class="cm"> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND</span>
|
||||
<span class="cm"> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE</span>
|
||||
<span class="cm"> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION</span>
|
||||
<span class="cm"> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION</span>
|
||||
<span class="cm"> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</span>
|
||||
|
||||
<span class="cm">*/</span>
|
||||
|
||||
<span class="kd">var</span> <span class="nx">net</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'net'</span><span class="p">),</span>
|
||||
<span class="nx">HTTPParser</span> <span class="o">=</span> <span class="nx">process</span><span class="p">.</span><span class="nx">binding</span><span class="p">(</span><span class="s1">'http_parser'</span><span class="p">).</span><span class="nx">HTTPParser</span><span class="p">,</span>
|
||||
<span class="nx">streams</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'morestreams'</span><span class="p">);</span>
|
||||
|
||||
<span class="nx">exports</span><span class="p">.</span><span class="nx">createServer</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">args</span> <span class="o">=</span> <span class="nb">Array</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">slice</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="nx">arguments</span><span class="p">),</span>
|
||||
<span class="nx">callback</span> <span class="o">=</span> <span class="k">typeof</span> <span class="nx">args</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">===</span> <span class="s1">'function'</span> <span class="o">&&</span> <span class="nx">args</span><span class="p">.</span><span class="nx">shift</span><span class="p">(),</span>
|
||||
<span class="nx">options</span> <span class="o">=</span> <span class="p">{},</span> <span class="nx">port</span><span class="p">,</span> <span class="nx">host</span><span class="p">,</span> <span class="nx">server</span><span class="p">;</span>
|
||||
|
||||
<span class="nx">server</span> <span class="o">=</span> <span class="nx">net</span><span class="p">.</span><span class="nx">createServer</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">socket</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">buffer</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">streams</span><span class="p">.</span><span class="nx">BufferedStream</span><span class="p">(),</span>
|
||||
<span class="nx">parser</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">HTTPParser</span><span class="p">(</span><span class="s1">'request'</span><span class="p">);</span>
|
||||
|
||||
<span class="nx">parser</span><span class="p">.</span><span class="nx">onHeaderField</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">b</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">len</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">slice</span> <span class="o">=</span> <span class="nx">b</span><span class="p">.</span><span class="nx">toString</span><span class="p">(</span><span class="s1">'ascii'</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">start</span> <span class="o">+</span> <span class="nx">len</span><span class="p">).</span><span class="nx">toLowerCase</span><span class="p">();</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">parser</span><span class="p">.</span><span class="nx">value</span> <span class="o">!=</span> <span class="kc">undefined</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">require</span><span class="p">(</span><span class="s1">'eyes'</span><span class="p">).</span><span class="nx">inspect</span><span class="p">(</span><span class="nx">parser</span><span class="p">.</span><span class="nx">value</span><span class="p">,</span> <span class="nx">parser</span><span class="p">.</span><span class="nx">field</span><span class="p">);</span>
|
||||
<span class="nx">parser</span><span class="p">.</span><span class="nx">field</span> <span class="o">=</span> <span class="kc">null</span><span class="p">;</span>
|
||||
<span class="nx">parser</span><span class="p">.</span><span class="nx">value</span> <span class="o">=</span> <span class="kc">null</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">parser</span><span class="p">.</span><span class="nx">field</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">parser</span><span class="p">.</span><span class="nx">field</span> <span class="o">+=</span> <span class="nx">slice</span><span class="p">;</span>
|
||||
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
|
||||
<span class="nx">parser</span><span class="p">.</span><span class="nx">field</span> <span class="o">=</span> <span class="nx">slice</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">};</span>
|
||||
|
||||
<span class="nx">parser</span><span class="p">.</span><span class="nx">onHeaderValue</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">b</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">len</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">slice</span> <span class="o">=</span> <span class="nx">b</span><span class="p">.</span><span class="nx">toString</span><span class="p">(</span><span class="s1">'ascii'</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">start</span> <span class="o">+</span> <span class="nx">len</span><span class="p">);</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">parser</span><span class="p">.</span><span class="nx">value</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">parser</span><span class="p">.</span><span class="nx">value</span> <span class="o">+=</span> <span class="nx">slice</span><span class="p">;</span>
|
||||
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
|
||||
<span class="nx">parser</span><span class="p">.</span><span class="nx">value</span> <span class="o">=</span> <span class="nx">slice</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">};</span>
|
||||
|
||||
<span class="nx">parser</span><span class="p">.</span><span class="nx">socket</span> <span class="o">=</span> <span class="nx">socket</span><span class="p">;</span>
|
||||
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">ondata</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">d</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">end</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">ret</span> <span class="o">=</span> <span class="nx">parser</span><span class="p">.</span><span class="nx">execute</span><span class="p">(</span><span class="nx">d</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">end</span> <span class="o">-</span> <span class="nx">start</span><span class="p">);</span>
|
||||
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">ret</span><span class="p">);</span>
|
||||
<span class="p">};</span>
|
||||
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">onend</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">ret</span> <span class="o">=</span> <span class="nx">parser</span><span class="p">.</span><span class="nx">finish</span><span class="p">();</span>
|
||||
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">ret</span> <span class="k">instanceof</span> <span class="nb">Error</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">destroy</span><span class="p">(</span><span class="nx">ret</span><span class="p">);</span>
|
||||
<span class="k">return</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">socket</span><span class="p">.</span><span class="nx">writable</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">};</span>
|
||||
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="s1">'hello world'</span><span class="p">);</span>
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="p">});</span>
|
||||
|
||||
<span class="k">return</span> <span class="nx">server</span><span class="p">;</span>
|
||||
<span class="p">};</span>
|
||||
|
||||
</pre></div> </td> </tr> </tbody> </table> </div> </body> </html>
|
||||
194
docs/docco.css
194
docs/docco.css
@ -1,194 +0,0 @@
|
||||
/*--------------------- Layout and Typography ----------------------------*/
|
||||
body {
|
||||
font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif;
|
||||
font-size: 15px;
|
||||
line-height: 22px;
|
||||
color: #252519;
|
||||
margin: 0; padding: 0;
|
||||
}
|
||||
a {
|
||||
color: #261a3b;
|
||||
}
|
||||
a:visited {
|
||||
color: #261a3b;
|
||||
}
|
||||
p {
|
||||
margin: 0 0 15px 0;
|
||||
}
|
||||
h4, h5, h6 {
|
||||
color: #333;
|
||||
margin: 6px 0 6px 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
h2, h3 {
|
||||
margin-bottom: 0;
|
||||
color: #000;
|
||||
}
|
||||
h1 {
|
||||
margin-top: 40px;
|
||||
margin-bottom: 15px;
|
||||
color: #000;
|
||||
}
|
||||
#container {
|
||||
position: relative;
|
||||
}
|
||||
#background {
|
||||
position: fixed;
|
||||
top: 0; left: 525px; right: 0; bottom: 0;
|
||||
background: #f5f5ff;
|
||||
border-left: 1px solid #e5e5ee;
|
||||
z-index: -1;
|
||||
}
|
||||
#jump_to, #jump_page {
|
||||
background: white;
|
||||
-webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777;
|
||||
-webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px;
|
||||
font: 10px Arial;
|
||||
text-transform: uppercase;
|
||||
cursor: pointer;
|
||||
text-align: right;
|
||||
}
|
||||
#jump_to, #jump_wrapper {
|
||||
position: fixed;
|
||||
right: 0; top: 0;
|
||||
padding: 5px 10px;
|
||||
}
|
||||
#jump_wrapper {
|
||||
padding: 0;
|
||||
display: none;
|
||||
}
|
||||
#jump_to:hover #jump_wrapper {
|
||||
display: block;
|
||||
}
|
||||
#jump_page {
|
||||
padding: 5px 0 3px;
|
||||
margin: 0 0 25px 25px;
|
||||
}
|
||||
#jump_page .source {
|
||||
display: block;
|
||||
padding: 5px 10px;
|
||||
text-decoration: none;
|
||||
border-top: 1px solid #eee;
|
||||
}
|
||||
#jump_page .source:hover {
|
||||
background: #f5f5ff;
|
||||
}
|
||||
#jump_page .source:first-child {
|
||||
}
|
||||
table td {
|
||||
border: 0;
|
||||
outline: 0;
|
||||
}
|
||||
td.docs, th.docs {
|
||||
max-width: 450px;
|
||||
min-width: 450px;
|
||||
min-height: 5px;
|
||||
padding: 10px 25px 1px 50px;
|
||||
overflow-x: hidden;
|
||||
vertical-align: top;
|
||||
text-align: left;
|
||||
}
|
||||
.docs pre {
|
||||
margin: 15px 0 15px;
|
||||
padding-left: 15px;
|
||||
}
|
||||
.docs p tt, .docs p code {
|
||||
background: #f8f8ff;
|
||||
border: 1px solid #dedede;
|
||||
font-size: 12px;
|
||||
padding: 0 0.2em;
|
||||
}
|
||||
.pilwrap {
|
||||
position: relative;
|
||||
}
|
||||
.pilcrow {
|
||||
font: 12px Arial;
|
||||
text-decoration: none;
|
||||
color: #454545;
|
||||
position: absolute;
|
||||
top: 3px; left: -20px;
|
||||
padding: 1px 2px;
|
||||
opacity: 0;
|
||||
-webkit-transition: opacity 0.2s linear;
|
||||
}
|
||||
td.docs:hover .pilcrow {
|
||||
opacity: 1;
|
||||
}
|
||||
td.code, th.code {
|
||||
padding: 14px 15px 16px 25px;
|
||||
width: 100%;
|
||||
vertical-align: top;
|
||||
background: #f5f5ff;
|
||||
border-left: 1px solid #e5e5ee;
|
||||
}
|
||||
pre, tt, code {
|
||||
font-size: 12px; line-height: 18px;
|
||||
font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace;
|
||||
margin: 0; padding: 0;
|
||||
}
|
||||
|
||||
|
||||
/*---------------------- Syntax Highlighting -----------------------------*/
|
||||
td.linenos { background-color: #f0f0f0; padding-right: 10px; }
|
||||
span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }
|
||||
body .hll { background-color: #ffffcc }
|
||||
body .c { color: #408080; font-style: italic } /* Comment */
|
||||
body .err { border: 1px solid #FF0000 } /* Error */
|
||||
body .k { color: #954121 } /* Keyword */
|
||||
body .o { color: #666666 } /* Operator */
|
||||
body .cm { color: #408080; font-style: italic } /* Comment.Multiline */
|
||||
body .cp { color: #BC7A00 } /* Comment.Preproc */
|
||||
body .c1 { color: #408080; font-style: italic } /* Comment.Single */
|
||||
body .cs { color: #408080; font-style: italic } /* Comment.Special */
|
||||
body .gd { color: #A00000 } /* Generic.Deleted */
|
||||
body .ge { font-style: italic } /* Generic.Emph */
|
||||
body .gr { color: #FF0000 } /* Generic.Error */
|
||||
body .gh { color: #000080; font-weight: bold } /* Generic.Heading */
|
||||
body .gi { color: #00A000 } /* Generic.Inserted */
|
||||
body .go { color: #808080 } /* Generic.Output */
|
||||
body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
|
||||
body .gs { font-weight: bold } /* Generic.Strong */
|
||||
body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
|
||||
body .gt { color: #0040D0 } /* Generic.Traceback */
|
||||
body .kc { color: #954121 } /* Keyword.Constant */
|
||||
body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */
|
||||
body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */
|
||||
body .kp { color: #954121 } /* Keyword.Pseudo */
|
||||
body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */
|
||||
body .kt { color: #B00040 } /* Keyword.Type */
|
||||
body .m { color: #666666 } /* Literal.Number */
|
||||
body .s { color: #219161 } /* Literal.String */
|
||||
body .na { color: #7D9029 } /* Name.Attribute */
|
||||
body .nb { color: #954121 } /* Name.Builtin */
|
||||
body .nc { color: #0000FF; font-weight: bold } /* Name.Class */
|
||||
body .no { color: #880000 } /* Name.Constant */
|
||||
body .nd { color: #AA22FF } /* Name.Decorator */
|
||||
body .ni { color: #999999; font-weight: bold } /* Name.Entity */
|
||||
body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */
|
||||
body .nf { color: #0000FF } /* Name.Function */
|
||||
body .nl { color: #A0A000 } /* Name.Label */
|
||||
body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
|
||||
body .nt { color: #954121; font-weight: bold } /* Name.Tag */
|
||||
body .nv { color: #19469D } /* Name.Variable */
|
||||
body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
|
||||
body .w { color: #bbbbbb } /* Text.Whitespace */
|
||||
body .mf { color: #666666 } /* Literal.Number.Float */
|
||||
body .mh { color: #666666 } /* Literal.Number.Hex */
|
||||
body .mi { color: #666666 } /* Literal.Number.Integer */
|
||||
body .mo { color: #666666 } /* Literal.Number.Oct */
|
||||
body .sb { color: #219161 } /* Literal.String.Backtick */
|
||||
body .sc { color: #219161 } /* Literal.String.Char */
|
||||
body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */
|
||||
body .s2 { color: #219161 } /* Literal.String.Double */
|
||||
body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
|
||||
body .sh { color: #219161 } /* Literal.String.Heredoc */
|
||||
body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
|
||||
body .sx { color: #954121 } /* Literal.String.Other */
|
||||
body .sr { color: #BB6688 } /* Literal.String.Regex */
|
||||
body .s1 { color: #219161 } /* Literal.String.Single */
|
||||
body .ss { color: #19469D } /* Literal.String.Symbol */
|
||||
body .bp { color: #954121 } /* Name.Builtin.Pseudo */
|
||||
body .vc { color: #19469D } /* Name.Variable.Class */
|
||||
body .vg { color: #19469D } /* Name.Variable.Global */
|
||||
body .vi { color: #19469D } /* Name.Variable.Instance */
|
||||
body .il { color: #666666 } /* Literal.Number.Integer.Long */
|
||||
@ -1,591 +0,0 @@
|
||||
<!DOCTYPE html> <html> <head> <title>node-http-proxy.js</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" media="all" href="docco.css" /> </head> <body> <div id="container"> <div id="background"></div> <div id="jump_to"> Jump To … <div id="jump_wrapper"> <div id="jump_page"> <a class="source" href="node-http-proxy.html"> node-http-proxy.html </a> <a class="source" href="proxy-table.html"> proxy-table.html </a> </div> </div> </div> <table cellpadding="0" cellspacing="0"> <thead> <tr> <th class="docs"> <h1> node-http-proxy.js </h1> </th> <th class="code"> </th> </tr> </thead> <tbody> <tr id="section-1"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-1">¶</a> </div> </td> <td class="code"> <div class="highlight"><pre><span class="cm">/*</span>
|
||||
<span class="cm"> node-http-proxy.js: http proxy for node.js</span>
|
||||
|
||||
<span class="cm"> Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Marak Squires, Fedor Indutny </span>
|
||||
|
||||
<span class="cm"> Permission is hereby granted, free of charge, to any person obtaining</span>
|
||||
<span class="cm"> a copy of this software and associated documentation files (the</span>
|
||||
<span class="cm"> "Software"), to deal in the Software without restriction, including</span>
|
||||
<span class="cm"> without limitation the rights to use, copy, modify, merge, publish,</span>
|
||||
<span class="cm"> distribute, sublicense, and/or sell copies of the Software, and to</span>
|
||||
<span class="cm"> permit persons to whom the Software is furnished to do so, subject to</span>
|
||||
<span class="cm"> the following conditions:</span>
|
||||
|
||||
<span class="cm"> The above copyright notice and this permission notice shall be</span>
|
||||
<span class="cm"> included in all copies or substantial portions of the Software.</span>
|
||||
|
||||
<span class="cm"> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,</span>
|
||||
<span class="cm"> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF</span>
|
||||
<span class="cm"> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND</span>
|
||||
<span class="cm"> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE</span>
|
||||
<span class="cm"> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION</span>
|
||||
<span class="cm"> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION</span>
|
||||
<span class="cm"> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</span>
|
||||
|
||||
<span class="cm">*/</span>
|
||||
|
||||
<span class="kd">var</span> <span class="nx">util</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'util'</span><span class="p">),</span>
|
||||
<span class="nx">http</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'http'</span><span class="p">),</span>
|
||||
<span class="nx">https</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'https'</span><span class="p">),</span>
|
||||
<span class="nx">events</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'events'</span><span class="p">),</span>
|
||||
<span class="nx">ProxyTable</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'./proxy-table'</span><span class="p">).</span><span class="nx">ProxyTable</span><span class="p">,</span>
|
||||
<span class="nx">maxSockets</span> <span class="o">=</span> <span class="mi">100</span><span class="p">;</span></pre></div> </td> </tr> <tr id="section-2"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-2">¶</a> </div> <h3>Version 0.5.7 // 5/19/2011</h3> </td> <td class="code"> <div class="highlight"><pre><span class="nx">exports</span><span class="p">.</span><span class="nx">version</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">];</span></pre></div> </td> </tr> <tr id="section-3"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-3">¶</a> </div> <p>Track our own list of agents internal to <code>node-http-proxy</code></p> </td> <td class="code"> <div class="highlight"><pre><span class="kd">var</span> <span class="nx">_agents</span> <span class="o">=</span> <span class="p">{};</span></pre></div> </td> </tr> <tr id="section-4"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-4">¶</a> </div> <h3>function _getAgent (host, port, secure)</h3>
|
||||
|
||||
<h4>@host {string} Host of the agent to get</h4>
|
||||
|
||||
<h4>@port {number} Port of the agent to get</h4>
|
||||
|
||||
<h4>@secure {boolean} Value indicating whether or not to use HTTPS</h4>
|
||||
|
||||
<p>Retreives an agent from the <code>http</code> or <code>https</code> module
|
||||
and sets the <code>maxSockets</code> property appropriately.</p> </td> <td class="code"> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">_getAgent</span> <span class="p">(</span><span class="nx">host</span><span class="p">,</span> <span class="nx">port</span><span class="p">,</span> <span class="nx">secure</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">Agent</span><span class="p">,</span> <span class="nx">id</span> <span class="o">=</span> <span class="p">[</span><span class="nx">host</span><span class="p">,</span> <span class="nx">port</span><span class="p">].</span><span class="nx">join</span><span class="p">(</span><span class="s1">':'</span><span class="p">);</span>
|
||||
|
||||
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">port</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">port</span> <span class="o">=</span> <span class="nx">secure</span> <span class="o">?</span> <span class="mi">443</span> <span class="o">:</span> <span class="mi">80</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">_agents</span><span class="p">[</span><span class="nx">id</span><span class="p">])</span> <span class="p">{</span>
|
||||
<span class="nx">Agent</span> <span class="o">=</span> <span class="nx">secure</span> <span class="o">?</span> <span class="nx">https</span><span class="p">.</span><span class="nx">Agent</span> <span class="o">:</span> <span class="nx">http</span><span class="p">.</span><span class="nx">Agent</span><span class="p">;</span>
|
||||
|
||||
<span class="nx">_agents</span><span class="p">[</span><span class="nx">id</span><span class="p">]</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Agent</span><span class="p">({</span>
|
||||
<span class="nx">host</span><span class="o">:</span> <span class="nx">host</span><span class="p">,</span>
|
||||
<span class="nx">port</span><span class="o">:</span> <span class="nx">port</span><span class="p">,</span>
|
||||
<span class="nx">maxSockets</span><span class="o">:</span> <span class="nx">maxSockets</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">return</span> <span class="nx">_agents</span><span class="p">[</span><span class="nx">id</span><span class="p">];</span>
|
||||
<span class="p">}</span></pre></div> </td> </tr> <tr id="section-5"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-5">¶</a> </div> <h3>function _getProtocol (secure, outgoing)</h3>
|
||||
|
||||
<h4>@secure {Object|boolean} Settings for <code>https</code></h4>
|
||||
|
||||
<h4>@outgoing {Object} Outgoing request options</h4>
|
||||
|
||||
<p>Returns the appropriate protocol based on the settings in
|
||||
<code>secure</code>. If the protocol is <code>https</code> this function will update
|
||||
the options in <code>outgoing</code> as appropriate by adding <code>ca</code>, <code>key</code>,
|
||||
and <code>cert</code> if they exist in <code>secure</code>.</p> </td> <td class="code"> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">_getProtocol</span> <span class="p">(</span><span class="nx">secure</span><span class="p">,</span> <span class="nx">outgoing</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">protocol</span> <span class="o">=</span> <span class="nx">secure</span> <span class="o">?</span> <span class="nx">https</span> <span class="o">:</span> <span class="nx">http</span><span class="p">;</span>
|
||||
|
||||
<span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nx">secure</span> <span class="o">===</span> <span class="s1">'object'</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">outgoing</span> <span class="o">=</span> <span class="nx">outgoing</span> <span class="o">||</span> <span class="p">{};</span>
|
||||
<span class="p">[</span><span class="s1">'ca'</span><span class="p">,</span> <span class="s1">'cert'</span><span class="p">,</span> <span class="s1">'key'</span><span class="p">].</span><span class="nx">forEach</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">prop</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">secure</span><span class="p">[</span><span class="nx">prop</span><span class="p">])</span> <span class="p">{</span>
|
||||
<span class="nx">outgoing</span><span class="p">[</span><span class="nx">prop</span><span class="p">]</span> <span class="o">=</span> <span class="nx">secure</span><span class="p">[</span><span class="nx">prop</span><span class="p">];</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">})</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">return</span> <span class="nx">protocol</span><span class="p">;</span>
|
||||
<span class="p">}</span></pre></div> </td> </tr> <tr id="section-6"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-6">¶</a> </div> <h3>function getMaxSockets ()</h3>
|
||||
|
||||
<p>Returns the maximum number of sockets
|
||||
allowed on <strong>every</strong> outgoing request
|
||||
made by <strong>all</strong> instances of <code>HttpProxy</code></p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">exports</span><span class="p">.</span><span class="nx">getMaxSockets</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
|
||||
<span class="k">return</span> <span class="nx">maxSockets</span><span class="p">;</span>
|
||||
<span class="p">};</span></pre></div> </td> </tr> <tr id="section-7"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-7">¶</a> </div> <h3>function setMaxSockets ()</h3>
|
||||
|
||||
<p>Sets the maximum number of sockets
|
||||
allowed on <strong>every</strong> outgoing request
|
||||
made by <strong>all</strong> instances of <code>HttpProxy</code></p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">exports</span><span class="p">.</span><span class="nx">setMaxSockets</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">value</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">maxSockets</span> <span class="o">=</span> <span class="nx">value</span><span class="p">;</span>
|
||||
<span class="p">};</span></pre></div> </td> </tr> <tr id="section-8"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-8">¶</a> </div> <h3>function createServer ([port, host, options, handler])</h3>
|
||||
|
||||
<h4>@port {number} <strong>Optional</strong> Port to use on the proxy target host.</h4>
|
||||
|
||||
<h4>@host {string} <strong>Optional</strong> Host of the proxy target.</h4>
|
||||
|
||||
<h4>@options {Object} <strong>Optional</strong> Options for the HttpProxy instance used</h4>
|
||||
|
||||
<h4>@handler {function} <strong>Optional</strong> Request handler for the server</h4>
|
||||
|
||||
<p>Returns a server that manages an instance of HttpProxy. Flexible arguments allow for:</p>
|
||||
|
||||
<ul>
|
||||
<li><code>httpProxy.createServer(9000, 'localhost')</code></li>
|
||||
<li>`httpProxy.createServer(9000, 'localhost', options)</li>
|
||||
<li><code>httpPRoxy.createServer(function (req, res, proxy) { ... })</code></li>
|
||||
</ul> </td> <td class="code"> <div class="highlight"><pre><span class="nx">exports</span><span class="p">.</span><span class="nx">createServer</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">args</span> <span class="o">=</span> <span class="nb">Array</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">slice</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="nx">arguments</span><span class="p">),</span>
|
||||
<span class="nx">callback</span> <span class="o">=</span> <span class="k">typeof</span> <span class="nx">args</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">===</span> <span class="s1">'function'</span> <span class="o">&&</span> <span class="nx">args</span><span class="p">.</span><span class="nx">shift</span><span class="p">(),</span>
|
||||
<span class="nx">options</span> <span class="o">=</span> <span class="p">{},</span> <span class="nx">port</span><span class="p">,</span> <span class="nx">host</span><span class="p">,</span> <span class="nx">forward</span><span class="p">,</span> <span class="nx">silent</span><span class="p">,</span> <span class="nx">proxy</span><span class="p">,</span> <span class="nx">server</span><span class="p">;</span>
|
||||
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">args</span><span class="p">.</span><span class="nx">length</span> <span class="o">>=</span> <span class="mi">2</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">port</span> <span class="o">=</span> <span class="nx">args</span><span class="p">[</span><span class="mi">0</span><span class="p">];</span>
|
||||
<span class="nx">host</span> <span class="o">=</span> <span class="nx">args</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
|
||||
<span class="nx">options</span> <span class="o">=</span> <span class="nx">args</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span> <span class="o">||</span> <span class="p">{};</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">args</span><span class="p">.</span><span class="nx">length</span> <span class="o">===</span> <span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">options</span> <span class="o">=</span> <span class="nx">args</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">||</span> <span class="p">{};</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">options</span><span class="p">.</span><span class="nx">router</span> <span class="o">&&</span> <span class="o">!</span><span class="nx">callback</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">throw</span> <span class="k">new</span> <span class="nb">Error</span><span class="p">(</span><span class="s1">'Cannot create server with no router and no callback'</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="nx">proxy</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">HttpProxy</span><span class="p">(</span><span class="nx">options</span><span class="p">);</span>
|
||||
|
||||
<span class="nx">handler</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">callback</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-9"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-9">¶</a> </div> <p>If we were passed a callback to process the request
|
||||
or response in some way, then call it.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">callback</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">,</span> <span class="nx">proxy</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">port</span> <span class="o">&&</span> <span class="nx">host</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-10"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-10">¶</a> </div> <p>If we have a target host and port for the request
|
||||
then proxy to the specified location.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">proxy</span><span class="p">.</span><span class="nx">proxyRequest</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">,</span> <span class="p">{</span>
|
||||
<span class="nx">port</span><span class="o">:</span> <span class="nx">port</span><span class="p">,</span>
|
||||
<span class="nx">host</span><span class="o">:</span> <span class="nx">host</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">proxy</span><span class="p">.</span><span class="nx">proxyTable</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-11"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-11">¶</a> </div> <p>If the proxy is configured with a ProxyTable
|
||||
instance then use that before failing.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">proxy</span><span class="p">.</span><span class="nx">proxyRequest</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">else</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-12"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-12">¶</a> </div> <p>Otherwise this server is improperly configured.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">throw</span> <span class="k">new</span> <span class="nb">Error</span><span class="p">(</span><span class="s1">'Cannot proxy without port, host, or router.'</span><span class="p">)</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">};</span>
|
||||
|
||||
<span class="nx">server</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">https</span>
|
||||
<span class="o">?</span> <span class="nx">https</span><span class="p">.</span><span class="nx">createServer</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">https</span><span class="p">,</span> <span class="nx">handler</span><span class="p">)</span>
|
||||
<span class="o">:</span> <span class="nx">http</span><span class="p">.</span><span class="nx">createServer</span><span class="p">(</span><span class="nx">handler</span><span class="p">);</span>
|
||||
|
||||
<span class="nx">server</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'close'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
|
||||
<span class="nx">proxy</span><span class="p">.</span><span class="nx">close</span><span class="p">();</span>
|
||||
<span class="p">});</span>
|
||||
|
||||
<span class="nx">proxy</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'routes'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">routes</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">server</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'routes'</span><span class="p">,</span> <span class="nx">routes</span><span class="p">);</span>
|
||||
<span class="p">});</span>
|
||||
|
||||
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">callback</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-13"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-13">¶</a> </div> <p>WebSocket support: if callback is empty tunnel
|
||||
websocket request automatically</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">server</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'upgrade'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">socket</span><span class="p">,</span> <span class="nx">head</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-14"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-14">¶</a> </div> <p>Tunnel websocket requests too</p> </td> <td class="code"> <div class="highlight"><pre>
|
||||
<span class="nx">proxy</span><span class="p">.</span><span class="nx">proxyWebSocketRequest</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">socket</span><span class="p">,</span> <span class="nx">head</span><span class="p">,</span> <span class="p">{</span>
|
||||
<span class="nx">port</span><span class="o">:</span> <span class="nx">port</span><span class="p">,</span>
|
||||
<span class="nx">host</span><span class="o">:</span> <span class="nx">host</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div> </td> </tr> <tr id="section-15"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-15">¶</a> </div> <p>Set the proxy on the server so it is available
|
||||
to the consumer of the server</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">server</span><span class="p">.</span><span class="nx">proxy</span> <span class="o">=</span> <span class="nx">proxy</span><span class="p">;</span>
|
||||
|
||||
<span class="k">return</span> <span class="nx">server</span><span class="p">;</span>
|
||||
<span class="p">};</span></pre></div> </td> </tr> <tr id="section-16"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-16">¶</a> </div> <h3>function HttpProxy (options)</h3>
|
||||
|
||||
<h4>@options {Object} Options for this instance.</h4>
|
||||
|
||||
<p>Constructor function for new instances of HttpProxy responsible
|
||||
for managing the life-cycle of streaming reverse proxyied HTTP requests.</p>
|
||||
|
||||
<p>Example options:</p>
|
||||
|
||||
<pre><code> {
|
||||
router: {
|
||||
'foo.com': 'localhost:8080',
|
||||
'bar.com': 'localhost:8081'
|
||||
},
|
||||
forward: {
|
||||
host: 'localhost',
|
||||
port: 9001
|
||||
}
|
||||
}
|
||||
</code></pre> </td> <td class="code"> <div class="highlight"><pre><span class="kd">var</span> <span class="nx">HttpProxy</span> <span class="o">=</span> <span class="nx">exports</span><span class="p">.</span><span class="nx">HttpProxy</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">events</span><span class="p">.</span><span class="nx">EventEmitter</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
|
||||
|
||||
<span class="kd">var</span> <span class="nx">self</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span>
|
||||
<span class="nx">options</span> <span class="o">=</span> <span class="nx">options</span> <span class="o">||</span> <span class="p">{};</span>
|
||||
</pre></div> </td> </tr> <tr id="section-17"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-17">¶</a> </div> <p>Setup basic proxying options</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">this</span><span class="p">.</span><span class="nx">https</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">https</span><span class="p">;</span>
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">forward</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">forward</span><span class="p">;</span>
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">target</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">target</span> <span class="o">||</span> <span class="p">{};</span>
|
||||
</pre></div> </td> </tr> <tr id="section-18"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-18">¶</a> </div> <p>Setup additional options for WebSocket proxying. When forcing
|
||||
the WebSocket handshake to change the <code>sec-websocket-location</code>
|
||||
and <code>sec-websocket-origin</code> headers <code>options.source</code> <strong>MUST</strong>
|
||||
be provided or the operation will fail with an <code>origin mismatch</code>
|
||||
by definition.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">this</span><span class="p">.</span><span class="nx">source</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">source</span> <span class="o">||</span> <span class="p">{</span> <span class="nx">host</span><span class="o">:</span> <span class="s1">'localhost'</span><span class="p">,</span> <span class="nx">port</span><span class="o">:</span> <span class="mi">8000</span> <span class="p">};</span>
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">changeOrigin</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">changeOrigin</span> <span class="o">||</span> <span class="kc">false</span><span class="p">;</span>
|
||||
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">router</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">proxyTable</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ProxyTable</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">router</span><span class="p">,</span> <span class="nx">options</span><span class="p">.</span><span class="nx">silent</span><span class="p">,</span> <span class="nx">options</span><span class="p">.</span><span class="nx">hostnameOnly</span><span class="p">);</span>
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">proxyTable</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'routes'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">routes</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">self</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'routes'</span><span class="p">,</span> <span class="nx">routes</span><span class="p">);</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">};</span></pre></div> </td> </tr> <tr id="section-19"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-19">¶</a> </div> <p>Inherit from events.EventEmitter</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">util</span><span class="p">.</span><span class="nx">inherits</span><span class="p">(</span><span class="nx">HttpProxy</span><span class="p">,</span> <span class="nx">events</span><span class="p">.</span><span class="nx">EventEmitter</span><span class="p">);</span></pre></div> </td> </tr> <tr id="section-20"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-20">¶</a> </div> <h3>function buffer (obj)</h3>
|
||||
|
||||
<h4>@obj {Object} Object to pause events from</h4>
|
||||
|
||||
<p>Buffer <code>data</code> and <code>end</code> events from the given <code>obj</code>.
|
||||
Consumers of HttpProxy performing async tasks
|
||||
<strong>must</strong> utilize this utility, to re-emit data once
|
||||
the async operation has completed, otherwise these
|
||||
<strong>events will be lost.</strong></p>
|
||||
|
||||
<pre><code> var buffer = httpProxy.buffer(req);
|
||||
fs.readFile(path, function(){
|
||||
httpProxy.proxyRequest(req, res, host, port, buffer);
|
||||
});
|
||||
</code></pre>
|
||||
|
||||
<p><strong>Attribution:</strong> This approach is based heavily on
|
||||
<a href="https://github.com/senchalabs/connect/blob/master/lib/utils.js#L157">Connect</a>.
|
||||
However, this is not a big leap from the implementation in node-http-proxy < 0.4.0.
|
||||
This simply chooses to manage the scope of the events on a new Object literal as opposed to
|
||||
<a href="https://github.com/nodejitsu/node-http-proxy/blob/v0.3.1/lib/node-http-proxy.js#L154">on the HttpProxy instance</a>.</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">HttpProxy</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">buffer</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">obj</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">onData</span><span class="p">,</span> <span class="nx">onEnd</span><span class="p">,</span> <span class="nx">events</span> <span class="o">=</span> <span class="p">[];</span>
|
||||
|
||||
<span class="nx">obj</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="nx">onData</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">data</span><span class="p">,</span> <span class="nx">encoding</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">events</span><span class="p">.</span><span class="nx">push</span><span class="p">([</span><span class="s1">'data'</span><span class="p">,</span> <span class="nx">data</span><span class="p">,</span> <span class="nx">encoding</span><span class="p">]);</span>
|
||||
<span class="p">});</span>
|
||||
|
||||
<span class="nx">obj</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'end'</span><span class="p">,</span> <span class="nx">onEnd</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">data</span><span class="p">,</span> <span class="nx">encoding</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">events</span><span class="p">.</span><span class="nx">push</span><span class="p">([</span><span class="s1">'end'</span><span class="p">,</span> <span class="nx">data</span><span class="p">,</span> <span class="nx">encoding</span><span class="p">]);</span>
|
||||
<span class="p">});</span>
|
||||
|
||||
<span class="k">return</span> <span class="p">{</span>
|
||||
<span class="nx">end</span><span class="o">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
|
||||
<span class="nx">obj</span><span class="p">.</span><span class="nx">removeListener</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="nx">onData</span><span class="p">);</span>
|
||||
<span class="nx">obj</span><span class="p">.</span><span class="nx">removeListener</span><span class="p">(</span><span class="s1">'end'</span><span class="p">,</span> <span class="nx">onEnd</span><span class="p">);</span>
|
||||
<span class="p">},</span>
|
||||
<span class="nx">resume</span><span class="o">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="nx">len</span> <span class="o">=</span> <span class="nx">events</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span> <span class="o"><</span> <span class="nx">len</span><span class="p">;</span> <span class="o">++</span><span class="nx">i</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">obj</span><span class="p">.</span><span class="nx">emit</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span><span class="nx">obj</span><span class="p">,</span> <span class="nx">events</span><span class="p">[</span><span class="nx">i</span><span class="p">]);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">};</span>
|
||||
<span class="p">};</span></pre></div> </td> </tr> <tr id="section-21"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-21">¶</a> </div> <h3>function close ()</h3>
|
||||
|
||||
<p>Frees the resources associated with this instance,
|
||||
if they exist. </p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">HttpProxy</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">close</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">proxyTable</span><span class="p">)</span> <span class="k">this</span><span class="p">.</span><span class="nx">proxyTable</span><span class="p">.</span><span class="nx">close</span><span class="p">();</span>
|
||||
<span class="p">};</span></pre></div> </td> </tr> <tr id="section-22"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-22">¶</a> </div> <h3>function proxyRequest (req, res, [port, host, paused])</h3>
|
||||
|
||||
<h4>@req {ServerRequest} Incoming HTTP Request to proxy.</h4>
|
||||
|
||||
<h4>@res {ServerResponse} Outgoing HTTP Request to write proxied data to.</h4>
|
||||
|
||||
<h4>@options {Object} Options for the outgoing proxy request.</h4>
|
||||
|
||||
<pre><code>options.port {number} Port to use on the proxy target host.
|
||||
options.host {string} Host of the proxy target.
|
||||
options.buffer {Object} Result from `httpProxy.buffer(req)`
|
||||
options.https {Object|boolean} Settings for https.
|
||||
</code></pre> </td> <td class="code"> <div class="highlight"><pre><span class="nx">HttpProxy</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">proxyRequest</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">,</span> <span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">self</span> <span class="o">=</span> <span class="k">this</span><span class="p">,</span> <span class="nx">errState</span> <span class="o">=</span> <span class="kc">false</span><span class="p">,</span> <span class="nx">location</span><span class="p">,</span> <span class="nx">outgoing</span><span class="p">,</span> <span class="nx">protocol</span><span class="p">,</span> <span class="nx">reverseProxy</span><span class="p">;</span>
|
||||
</pre></div> </td> </tr> <tr id="section-23"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-23">¶</a> </div> <p>Create an empty options hash if none is passed.
|
||||
If default options have been passed to the constructor
|
||||
of this instance, use them by default.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">options</span> <span class="o">=</span> <span class="nx">options</span> <span class="o">||</span> <span class="p">{};</span>
|
||||
<span class="nx">options</span><span class="p">.</span><span class="nx">host</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">host</span> <span class="o">||</span> <span class="k">this</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">host</span><span class="p">;</span>
|
||||
<span class="nx">options</span><span class="p">.</span><span class="nx">port</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">port</span> <span class="o">||</span> <span class="k">this</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">port</span><span class="p">;</span>
|
||||
</pre></div> </td> </tr> <tr id="section-24"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-24">¶</a> </div> <p>Check the proxy table for this instance to see if we need
|
||||
to get the proxy location for the request supplied. We will
|
||||
always ignore the proxyTable if an explicit <code>port</code> and <code>host</code>
|
||||
arguments are supplied to <code>proxyRequest</code>.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">proxyTable</span> <span class="o">&&</span> <span class="o">!</span><span class="nx">options</span><span class="p">.</span><span class="nx">host</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">location</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">proxyTable</span><span class="p">.</span><span class="nx">getProxyLocation</span><span class="p">(</span><span class="nx">req</span><span class="p">);</span>
|
||||
</pre></div> </td> </tr> <tr id="section-25"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-25">¶</a> </div> <p>If no location is returned from the ProxyTable instance
|
||||
then respond with <code>404</code> since we do not have a valid proxy target.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">location</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">res</span><span class="p">.</span><span class="nx">writeHead</span><span class="p">(</span><span class="mi">404</span><span class="p">);</span>
|
||||
<span class="k">return</span> <span class="nx">res</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div> </td> </tr> <tr id="section-26"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-26">¶</a> </div> <p>When using the ProxyTable in conjunction with an HttpProxy instance
|
||||
only the following arguments are valid:</p>
|
||||
|
||||
<ul>
|
||||
<li><code>proxy.proxyRequest(req, res, { host: 'localhost' })</code>: This will be skipped</li>
|
||||
<li><code>proxy.proxyRequest(req, res, { buffer: buffer })</code>: Buffer will get updated appropriately</li>
|
||||
<li><code>proxy.proxyRequest(req, res)</code>: Options will be assigned appropriately. </li>
|
||||
</ul> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">options</span><span class="p">.</span><span class="nx">port</span> <span class="o">=</span> <span class="nx">location</span><span class="p">.</span><span class="nx">port</span><span class="p">;</span>
|
||||
<span class="nx">options</span><span class="p">.</span><span class="nx">host</span> <span class="o">=</span> <span class="nx">location</span><span class="p">.</span><span class="nx">host</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div> </td> </tr> <tr id="section-27"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-27">¶</a> </div> <p>Add common proxy headers to the request so that they can
|
||||
be availible to the proxy target server:</p>
|
||||
|
||||
<ul>
|
||||
<li><code>x-forwarded-for</code>: IP Address of the original request</li>
|
||||
<li><code>x-forwarded-proto</code>: Protocol of the original request</li>
|
||||
<li><code>x-forwarded-port</code>: Port of the original request. </li>
|
||||
</ul> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">req</span><span class="p">.</span><span class="nx">headers</span><span class="p">[</span><span class="s1">'x-forwarded-for'</span><span class="p">]</span> <span class="o">=</span> <span class="nx">req</span><span class="p">.</span><span class="nx">connection</span><span class="p">.</span><span class="nx">remoteAddress</span> <span class="o">||</span> <span class="nx">req</span><span class="p">.</span><span class="nx">connection</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">remoteAddress</span><span class="p">;</span>
|
||||
<span class="nx">req</span><span class="p">.</span><span class="nx">headers</span><span class="p">[</span><span class="s1">'x-forwarded-port'</span><span class="p">]</span> <span class="o">=</span> <span class="nx">req</span><span class="p">.</span><span class="nx">connection</span><span class="p">.</span><span class="nx">remotePort</span> <span class="o">||</span> <span class="nx">req</span><span class="p">.</span><span class="nx">connection</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">remotePort</span><span class="p">;</span>
|
||||
<span class="nx">req</span><span class="p">.</span><span class="nx">headers</span><span class="p">[</span><span class="s1">'x-forwarded-proto'</span><span class="p">]</span> <span class="o">=</span> <span class="nx">res</span><span class="p">.</span><span class="nx">connection</span><span class="p">.</span><span class="nx">pair</span> <span class="o">?</span> <span class="s1">'https'</span> <span class="o">:</span> <span class="s1">'http'</span><span class="p">;</span>
|
||||
</pre></div> </td> </tr> <tr id="section-28"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-28">¶</a> </div> <p>Emit the <code>start</code> event indicating that we have begun the proxy operation.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">this</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'start'</span><span class="p">,</span> <span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">,</span> <span class="nx">options</span><span class="p">);</span>
|
||||
</pre></div> </td> </tr> <tr id="section-29"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-29">¶</a> </div> <p>If forwarding is enabled for this instance, foward proxy the
|
||||
specified request to the address provided in <code>this.forward</code></p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">forward</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'forward'</span><span class="p">,</span> <span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">forward</span><span class="p">);</span>
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">_forwardRequest</span><span class="p">(</span><span class="nx">req</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div> </td> </tr> <tr id="section-30"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-30">¶</a> </div> <h4>function proxyError (err)</h4>
|
||||
|
||||
<h4>@err {Error} Error contacting the proxy target</h4>
|
||||
|
||||
<p>Short-circuits <code>res</code> in the event of any error when
|
||||
contacting the proxy target at <code>host</code> / <code>port</code>.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="kd">function</span> <span class="nx">proxyError</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">errState</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
|
||||
</pre></div> </td> </tr> <tr id="section-31"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-31">¶</a> </div> <p>Emit an <code>error</code> event, allowing the application to use custom
|
||||
error handling. The error handler should end the response.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="nx">self</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'proxyError'</span><span class="p">,</span> <span class="nx">err</span><span class="p">,</span> <span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">))</span> <span class="p">{</span>
|
||||
<span class="k">return</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="nx">res</span><span class="p">.</span><span class="nx">writeHead</span><span class="p">(</span><span class="mi">500</span><span class="p">,</span> <span class="p">{</span> <span class="s1">'Content-Type'</span><span class="o">:</span> <span class="s1">'text/plain'</span> <span class="p">});</span>
|
||||
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">req</span><span class="p">.</span><span class="nx">method</span> <span class="o">!==</span> <span class="s1">'HEAD'</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-32"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-32">¶</a> </div> <p>This NODE_ENV=production behavior is mimics Express and
|
||||
Connect.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="nx">process</span><span class="p">.</span><span class="nx">env</span><span class="p">.</span><span class="nx">NODE_ENV</span> <span class="o">===</span> <span class="s1">'production'</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">res</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="s1">'Internal Server Error'</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">else</span> <span class="p">{</span>
|
||||
<span class="nx">res</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="s1">'An error has occurred: '</span> <span class="o">+</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">err</span><span class="p">));</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="nx">res</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="nx">outgoing</span> <span class="o">=</span> <span class="p">{</span>
|
||||
<span class="nx">host</span><span class="o">:</span> <span class="nx">options</span><span class="p">.</span><span class="nx">host</span><span class="p">,</span>
|
||||
<span class="nx">port</span><span class="o">:</span> <span class="nx">options</span><span class="p">.</span><span class="nx">port</span><span class="p">,</span>
|
||||
<span class="nx">agent</span><span class="o">:</span> <span class="nx">_getAgent</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">host</span><span class="p">,</span> <span class="nx">options</span><span class="p">.</span><span class="nx">port</span><span class="p">,</span> <span class="nx">options</span><span class="p">.</span><span class="nx">https</span> <span class="o">||</span> <span class="k">this</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">https</span><span class="p">),</span>
|
||||
<span class="nx">method</span><span class="o">:</span> <span class="nx">req</span><span class="p">.</span><span class="nx">method</span><span class="p">,</span>
|
||||
<span class="nx">path</span><span class="o">:</span> <span class="nx">req</span><span class="p">.</span><span class="nx">url</span><span class="p">,</span>
|
||||
<span class="nx">headers</span><span class="o">:</span> <span class="nx">req</span><span class="p">.</span><span class="nx">headers</span>
|
||||
<span class="p">};</span>
|
||||
|
||||
<span class="nx">protocol</span> <span class="o">=</span> <span class="nx">_getProtocol</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">https</span> <span class="o">||</span> <span class="k">this</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">https</span><span class="p">,</span> <span class="nx">outgoing</span><span class="p">);</span>
|
||||
</pre></div> </td> </tr> <tr id="section-33"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-33">¶</a> </div> <p>Open new HTTP request to internal resource with will act as a reverse proxy pass</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">reverseProxy</span> <span class="o">=</span> <span class="nx">protocol</span><span class="p">.</span><span class="nx">request</span><span class="p">(</span><span class="nx">outgoing</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">response</span><span class="p">)</span> <span class="p">{</span>
|
||||
</pre></div> </td> </tr> <tr id="section-34"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-34">¶</a> </div> <p>Process the <code>reverseProxy</code> <code>response</code> when it's received.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="nx">response</span><span class="p">.</span><span class="nx">headers</span><span class="p">.</span><span class="nx">connection</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">req</span><span class="p">.</span><span class="nx">headers</span><span class="p">.</span><span class="nx">connection</span><span class="p">)</span> <span class="nx">response</span><span class="p">.</span><span class="nx">headers</span><span class="p">.</span><span class="nx">connection</span> <span class="o">=</span> <span class="nx">req</span><span class="p">.</span><span class="nx">headers</span><span class="p">.</span><span class="nx">connection</span><span class="p">;</span>
|
||||
<span class="k">else</span> <span class="nx">response</span><span class="p">.</span><span class="nx">headers</span><span class="p">.</span><span class="nx">connection</span> <span class="o">=</span> <span class="s1">'close'</span><span class="p">;</span>
|
||||
<span class="p">}</span></pre></div> </td> </tr> <tr id="section-35"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-35">¶</a> </div> <p>Set the headers of the client response</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">res</span><span class="p">.</span><span class="nx">writeHead</span><span class="p">(</span><span class="nx">response</span><span class="p">.</span><span class="nx">statusCode</span><span class="p">,</span> <span class="nx">response</span><span class="p">.</span><span class="nx">headers</span><span class="p">);</span></pre></div> </td> </tr> <tr id="section-36"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-36">¶</a> </div> <p><code>response.statusCode === 304</code>: No 'data' event and no 'end'</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="nx">response</span><span class="p">.</span><span class="nx">statusCode</span> <span class="o">===</span> <span class="mi">304</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">return</span> <span class="nx">res</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="p">}</span></pre></div> </td> </tr> <tr id="section-37"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-37">¶</a> </div> <p>For each data <code>chunk</code> received from the <code>reverseProxy</code>
|
||||
<code>response</code> write it to the outgoing <code>res</code>.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">response</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">chunk</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">req</span><span class="p">.</span><span class="nx">method</span> <span class="o">!==</span> <span class="s1">'HEAD'</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">res</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">chunk</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">});</span></pre></div> </td> </tr> <tr id="section-38"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-38">¶</a> </div> <p>When the <code>reverseProxy</code> <code>response</code> ends, end the
|
||||
corresponding outgoing <code>res</code> unless we have entered
|
||||
an error state. In which case, assume <code>res.end()</code> has
|
||||
already been called and the 'error' event listener
|
||||
removed.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">response</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'end'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">errState</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">removeListener</span><span class="p">(</span><span class="s1">'error'</span><span class="p">,</span> <span class="nx">proxyError</span><span class="p">);</span>
|
||||
<span class="nx">res</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
</pre></div> </td> </tr> <tr id="section-39"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-39">¶</a> </div> <p>Emit the <code>end</code> event now that we have completed proxying</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">self</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'end'</span><span class="p">,</span> <span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">});</span>
|
||||
</pre></div> </td> </tr> <tr id="section-40"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-40">¶</a> </div> <p>Handle 'error' events from the <code>reverseProxy</code>.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">once</span><span class="p">(</span><span class="s1">'error'</span><span class="p">,</span> <span class="nx">proxyError</span><span class="p">);</span>
|
||||
</pre></div> </td> </tr> <tr id="section-41"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-41">¶</a> </div> <p>For each data <code>chunk</code> received from the incoming
|
||||
<code>req</code> write it to the <code>reverseProxy</code> request.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">req</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">chunk</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">errState</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">chunk</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">});</span></pre></div> </td> </tr> <tr id="section-42"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-42">¶</a> </div> <p>When the incoming <code>req</code> ends, end the corresponding <code>reverseProxy</code>
|
||||
request unless we have entered an error state. </p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">req</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'end'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">errState</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">});</span></pre></div> </td> </tr> <tr id="section-43"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-43">¶</a> </div> <p>If we have been passed buffered data, resume it.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">buffer</span> <span class="o">&&</span> <span class="o">!</span><span class="nx">errState</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">options</span><span class="p">.</span><span class="nx">buffer</span><span class="p">.</span><span class="nx">resume</span><span class="p">();</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">};</span>
|
||||
</pre></div> </td> </tr> <tr id="section-44"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-44">¶</a> </div> <h3>@private function _forwardRequest (req)</h3>
|
||||
|
||||
<h4>@req {ServerRequest} Incoming HTTP Request to proxy.</h4>
|
||||
|
||||
<p>Forwards the specified <code>req</code> to the location specified
|
||||
by <code>this.forward</code> ignoring errors and the subsequent response.</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">HttpProxy</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">_forwardRequest</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">req</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">self</span> <span class="o">=</span> <span class="k">this</span><span class="p">,</span> <span class="nx">port</span><span class="p">,</span> <span class="nx">host</span><span class="p">,</span> <span class="nx">outgoing</span><span class="p">,</span> <span class="nx">protocol</span><span class="p">,</span> <span class="nx">forwardProxy</span><span class="p">;</span>
|
||||
|
||||
<span class="nx">port</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">forward</span><span class="p">.</span><span class="nx">port</span><span class="p">;</span>
|
||||
<span class="nx">host</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">forward</span><span class="p">.</span><span class="nx">host</span><span class="p">;</span>
|
||||
|
||||
<span class="nx">outgoing</span> <span class="o">=</span> <span class="p">{</span>
|
||||
<span class="nx">host</span><span class="o">:</span> <span class="nx">host</span><span class="p">,</span>
|
||||
<span class="nx">port</span><span class="o">:</span> <span class="nx">port</span><span class="p">,</span>
|
||||
<span class="nx">agent</span><span class="o">:</span> <span class="nx">_getAgent</span><span class="p">(</span><span class="nx">host</span><span class="p">,</span> <span class="nx">port</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">forward</span><span class="p">.</span><span class="nx">https</span><span class="p">),</span>
|
||||
<span class="nx">method</span><span class="o">:</span> <span class="nx">req</span><span class="p">.</span><span class="nx">method</span><span class="p">,</span>
|
||||
<span class="nx">path</span><span class="o">:</span> <span class="nx">req</span><span class="p">.</span><span class="nx">url</span><span class="p">,</span>
|
||||
<span class="nx">headers</span><span class="o">:</span> <span class="nx">req</span><span class="p">.</span><span class="nx">headers</span>
|
||||
<span class="p">};</span>
|
||||
</pre></div> </td> </tr> <tr id="section-45"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-45">¶</a> </div> <p>Force the <code>connection</code> header to be 'close' until
|
||||
node.js core re-implements 'keep-alive'.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">outgoing</span><span class="p">.</span><span class="nx">headers</span><span class="p">[</span><span class="s1">'connection'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'close'</span><span class="p">;</span>
|
||||
|
||||
<span class="nx">protocol</span> <span class="o">=</span> <span class="nx">_getProtocol</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">forward</span><span class="p">.</span><span class="nx">https</span><span class="p">,</span> <span class="nx">outgoing</span><span class="p">);</span>
|
||||
</pre></div> </td> </tr> <tr id="section-46"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-46">¶</a> </div> <p>Open new HTTP request to internal resource with will act as a reverse proxy pass</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">forwardProxy</span> <span class="o">=</span> <span class="nx">protocol</span><span class="p">.</span><span class="nx">request</span><span class="p">(</span><span class="nx">outgoing</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">response</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-47"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-47">¶</a> </div> <p>Ignore the response from the forward proxy since this is a 'fire-and-forget' proxy.
|
||||
Remark (indexzero): We will eventually emit a 'forward' event here for performance tuning.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="p">});</span>
|
||||
</pre></div> </td> </tr> <tr id="section-48"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-48">¶</a> </div> <p>Add a listener for the connection timeout event.</p>
|
||||
|
||||
<p>Remark: Ignoring this error in the event
|
||||
forward target doesn't exist.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">forwardProxy</span><span class="p">.</span><span class="nx">once</span><span class="p">(</span><span class="s1">'error'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span> <span class="p">});</span></pre></div> </td> </tr> <tr id="section-49"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-49">¶</a> </div> <p>Chunk the client request body as chunks from the proxied request come in</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">req</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">chunk</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">forwardProxy</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">chunk</span><span class="p">);</span>
|
||||
<span class="p">})</span></pre></div> </td> </tr> <tr id="section-50"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-50">¶</a> </div> <p>At the end of the client request, we are going to stop the proxied request</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">req</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'end'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
|
||||
<span class="nx">forwardProxy</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">};</span></pre></div> </td> </tr> <tr id="section-51"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-51">¶</a> </div> <h3>function proxyWebSocketRequest (req, socket, head, options)</h3>
|
||||
|
||||
<h4>@req {ServerRequest} Websocket request to proxy.</h4>
|
||||
|
||||
<h4>@socket {net.Socket} Socket for the underlying HTTP request</h4>
|
||||
|
||||
<h4>@head {string} Headers for the Websocket request.</h4>
|
||||
|
||||
<h4>@options {Object} Options to use when proxying this request.</h4>
|
||||
|
||||
<pre><code>options.port {number} Port to use on the proxy target host.
|
||||
options.host {string} Host of the proxy target.
|
||||
options.buffer {Object} Result from `httpProxy.buffer(req)`
|
||||
options.https {Object|boolean} Settings for https.
|
||||
</code></pre> </td> <td class="code"> <div class="highlight"><pre><span class="nx">HttpProxy</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">proxyWebSocketRequest</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">socket</span><span class="p">,</span> <span class="nx">head</span><span class="p">,</span> <span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">self</span> <span class="o">=</span> <span class="k">this</span><span class="p">,</span>
|
||||
<span class="nx">listeners</span> <span class="o">=</span> <span class="p">{},</span>
|
||||
<span class="nx">errState</span> <span class="o">=</span> <span class="kc">false</span><span class="p">,</span>
|
||||
<span class="nx">CRLF</span> <span class="o">=</span> <span class="s1">'\r\n'</span><span class="p">,</span>
|
||||
<span class="nx">outgoing</span><span class="p">;</span></pre></div> </td> </tr> <tr id="section-52"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-52">¶</a> </div> <p>WebSocket requests must have the <code>GET</code> method and
|
||||
the <code>upgrade:websocket</code> header</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="nx">req</span><span class="p">.</span><span class="nx">method</span> <span class="o">!==</span> <span class="s1">'GET'</span> <span class="o">||</span> <span class="nx">req</span><span class="p">.</span><span class="nx">headers</span><span class="p">.</span><span class="nx">upgrade</span><span class="p">.</span><span class="nx">toLowerCase</span><span class="p">()</span> <span class="o">!==</span> <span class="s1">'websocket'</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-53"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-53">¶</a> </div> <p>This request is not WebSocket request</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">return</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div> </td> </tr> <tr id="section-54"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-54">¶</a> </div> <p>Helper function for setting appropriate socket values:
|
||||
1. Turn of all bufferings
|
||||
2. For server set KeepAlive
|
||||
3. For client set encoding</p> </td> <td class="code"> <div class="highlight"><pre> <span class="kd">function</span> <span class="nx">_socket</span><span class="p">(</span><span class="nx">socket</span><span class="p">,</span> <span class="nx">keepAlive</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">setTimeout</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">setNoDelay</span><span class="p">(</span><span class="kc">true</span><span class="p">);</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">keepAlive</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">socket</span><span class="p">.</span><span class="nx">setKeepAlive</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">setKeepAlive</span><span class="p">(</span><span class="kc">true</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">socket</span><span class="p">.</span><span class="nx">pair</span><span class="p">.</span><span class="nx">cleartext</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">setKeepAlive</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">pair</span><span class="p">.</span><span class="nx">cleartext</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">setKeepAlive</span><span class="p">(</span><span class="kc">true</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">else</span> <span class="p">{</span>
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">setEncoding</span><span class="p">(</span><span class="s1">'utf8'</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div> </td> </tr> <tr id="section-55"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-55">¶</a> </div> <p>On <code>upgrade</code> from the Agent socket, listen to
|
||||
the appropriate events.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="kd">function</span> <span class="nx">onUpgrade</span> <span class="p">(</span><span class="nx">reverseProxy</span><span class="p">,</span> <span class="nx">proxySocket</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">reverseProxy</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">proxySocket</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="k">return</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div> </td> </tr> <tr id="section-56"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-56">¶</a> </div> <p>Any incoming data on this WebSocket to the proxy target
|
||||
will be written to the <code>reverseProxy</code> socket.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">proxySocket</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="nx">listeners</span><span class="p">.</span><span class="nx">onIncoming</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">incoming</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">writable</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">try</span> <span class="p">{</span>
|
||||
<span class="nx">self</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'websocket:outgoing'</span><span class="p">,</span> <span class="nx">req</span><span class="p">,</span> <span class="nx">socket</span><span class="p">,</span> <span class="nx">head</span><span class="p">,</span> <span class="nx">data</span><span class="p">);</span>
|
||||
<span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">incoming</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">catch</span> <span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">incoming</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="nx">proxySocket</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">});</span></pre></div> </td> </tr> <tr id="section-57"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-57">¶</a> </div> <p>Any outgoing data on this Websocket from the proxy target
|
||||
will be written to the <code>proxySocket</code> socket.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">incoming</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="nx">listeners</span><span class="p">.</span><span class="nx">onOutgoing</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">try</span> <span class="p">{</span>
|
||||
<span class="nx">self</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'websocket:incoming'</span><span class="p">,</span> <span class="nx">reverseProxy</span><span class="p">,</span> <span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">incoming</span><span class="p">,</span> <span class="nx">head</span><span class="p">,</span> <span class="nx">data</span><span class="p">);</span>
|
||||
<span class="nx">proxySocket</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">catch</span> <span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">proxySocket</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">});</span>
|
||||
</pre></div> </td> </tr> <tr id="section-58"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-58">¶</a> </div> <p>Helper function to detach all event listeners
|
||||
from <code>reverseProxy</code> and <code>proxySocket</code>.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="kd">function</span> <span class="nx">detach</span><span class="p">()</span> <span class="p">{</span>
|
||||
<span class="nx">proxySocket</span><span class="p">.</span><span class="nx">removeListener</span><span class="p">(</span><span class="s1">'end'</span><span class="p">,</span> <span class="nx">listeners</span><span class="p">.</span><span class="nx">onIncomingClose</span><span class="p">);</span>
|
||||
<span class="nx">proxySocket</span><span class="p">.</span><span class="nx">removeListener</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="nx">listeners</span><span class="p">.</span><span class="nx">onIncoming</span><span class="p">);</span>
|
||||
<span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">incoming</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">removeListener</span><span class="p">(</span><span class="s1">'end'</span><span class="p">,</span> <span class="nx">listeners</span><span class="p">.</span><span class="nx">onOutgoingClose</span><span class="p">);</span>
|
||||
<span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">incoming</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">removeListener</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="nx">listeners</span><span class="p">.</span><span class="nx">onOutgoing</span><span class="p">);</span>
|
||||
<span class="p">}</span></pre></div> </td> </tr> <tr id="section-59"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-59">¶</a> </div> <p>If the incoming <code>proxySocket</code> socket closes, then
|
||||
detach all event listeners. </p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">proxySocket</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'end'</span><span class="p">,</span> <span class="nx">listeners</span><span class="p">.</span><span class="nx">onIncomingClose</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
|
||||
<span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">incoming</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="nx">detach</span><span class="p">();</span>
|
||||
</pre></div> </td> </tr> <tr id="section-60"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-60">¶</a> </div> <p>Emit the <code>end</code> event now that we have completed proxying</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">self</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'websocket:end'</span><span class="p">,</span> <span class="nx">req</span><span class="p">,</span> <span class="nx">socket</span><span class="p">,</span> <span class="nx">head</span><span class="p">);</span>
|
||||
<span class="p">});</span></pre></div> </td> </tr> <tr id="section-61"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-61">¶</a> </div> <p>If the <code>reverseProxy</code> socket closes, then detach all
|
||||
event listeners.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">incoming</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'end'</span><span class="p">,</span> <span class="nx">listeners</span><span class="p">.</span><span class="nx">onOutgoingClose</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
|
||||
<span class="nx">proxySocket</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="nx">detach</span><span class="p">();</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">};</span></pre></div> </td> </tr> <tr id="section-62"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-62">¶</a> </div> <p>Setup the incoming client socket.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">_socket</span><span class="p">(</span><span class="nx">socket</span><span class="p">);</span>
|
||||
|
||||
<span class="kd">function</span> <span class="nx">getPort</span> <span class="p">(</span><span class="nx">port</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">port</span> <span class="o">=</span> <span class="nx">port</span> <span class="o">||</span> <span class="mi">80</span><span class="p">;</span>
|
||||
<span class="k">return</span> <span class="nx">port</span> <span class="o">-</span> <span class="mi">80</span> <span class="o">===</span> <span class="mi">0</span> <span class="o">?</span> <span class="s1">''</span> <span class="o">:</span> <span class="s1">':'</span> <span class="o">+</span> <span class="nx">port</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div> </td> </tr> <tr id="section-63"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-63">¶</a> </div> <p>Get the protocol, and host for this request and create an instance
|
||||
of <code>http.Agent</code> or <code>https.Agent</code> from the pool managed by <code>node-http-proxy</code>.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="kd">var</span> <span class="nx">protocolName</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">https</span> <span class="o">||</span> <span class="k">this</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">https</span> <span class="o">?</span> <span class="s1">'https'</span> <span class="o">:</span> <span class="s1">'http'</span><span class="p">,</span>
|
||||
<span class="nx">portUri</span> <span class="o">=</span> <span class="nx">getPort</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">source</span><span class="p">.</span><span class="nx">port</span><span class="p">),</span>
|
||||
<span class="nx">remoteHost</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">host</span> <span class="o">+</span> <span class="nx">portUri</span><span class="p">,</span>
|
||||
<span class="nx">agent</span> <span class="o">=</span> <span class="nx">_getAgent</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">host</span><span class="p">,</span> <span class="nx">options</span><span class="p">.</span><span class="nx">port</span><span class="p">,</span> <span class="nx">options</span><span class="p">.</span><span class="nx">https</span> <span class="o">||</span> <span class="k">this</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">https</span><span class="p">);</span></pre></div> </td> </tr> <tr id="section-64"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-64">¶</a> </div> <p>Change headers (if requested).</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">changeOrigin</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">req</span><span class="p">.</span><span class="nx">headers</span><span class="p">.</span><span class="nx">host</span> <span class="o">=</span> <span class="nx">remoteHost</span><span class="p">;</span>
|
||||
<span class="nx">req</span><span class="p">.</span><span class="nx">headers</span><span class="p">.</span><span class="nx">origin</span> <span class="o">=</span> <span class="nx">protocolName</span> <span class="o">+</span> <span class="s1">'://'</span> <span class="o">+</span> <span class="nx">remoteHost</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div> </td> </tr> <tr id="section-65"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-65">¶</a> </div> <p>Make the outgoing WebSocket request</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">outgoing</span> <span class="o">=</span> <span class="p">{</span>
|
||||
<span class="nx">host</span><span class="o">:</span> <span class="nx">options</span><span class="p">.</span><span class="nx">host</span><span class="p">,</span>
|
||||
<span class="nx">port</span><span class="o">:</span> <span class="nx">options</span><span class="p">.</span><span class="nx">port</span><span class="p">,</span>
|
||||
<span class="nx">method</span><span class="o">:</span> <span class="s1">'GET'</span><span class="p">,</span>
|
||||
<span class="nx">path</span><span class="o">:</span> <span class="nx">req</span><span class="p">.</span><span class="nx">url</span><span class="p">,</span>
|
||||
<span class="nx">headers</span><span class="o">:</span> <span class="nx">req</span><span class="p">.</span><span class="nx">headers</span><span class="p">,</span>
|
||||
<span class="p">};</span>
|
||||
<span class="kd">var</span> <span class="nx">reverseProxy</span> <span class="o">=</span> <span class="nx">agent</span><span class="p">.</span><span class="nx">appendMessage</span><span class="p">(</span><span class="nx">outgoing</span><span class="p">);</span></pre></div> </td> </tr> <tr id="section-66"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-66">¶</a> </div> <p>On any errors from the <code>reverseProxy</code> emit the
|
||||
<code>webSocketProxyError</code> and close the appropriate
|
||||
connections.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="kd">function</span> <span class="nx">proxyError</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">self</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'webSocketProxyError'</span><span class="p">,</span> <span class="nx">req</span><span class="p">,</span> <span class="nx">socket</span><span class="p">,</span> <span class="nx">head</span><span class="p">))</span> <span class="p">{</span>
|
||||
<span class="k">return</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
|
||||
<span class="p">}</span></pre></div> </td> </tr> <tr id="section-67"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-67">¶</a> </div> <p>Here we set the incoming <code>req</code>, <code>socket</code> and <code>head</code> data to the outgoing
|
||||
request so that we can reuse this data later on in the closure scope
|
||||
available to the <code>upgrade</code> event. This bookkeeping is not tracked anywhere
|
||||
in nodejs core and is <strong>very</strong> specific to proxying WebSockets.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">agent</span> <span class="o">=</span> <span class="nx">agent</span><span class="p">;</span>
|
||||
<span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">incoming</span> <span class="o">=</span> <span class="p">{</span>
|
||||
<span class="nx">request</span><span class="o">:</span> <span class="nx">req</span><span class="p">,</span>
|
||||
<span class="nx">socket</span><span class="o">:</span> <span class="nx">socket</span><span class="p">,</span>
|
||||
<span class="nx">head</span><span class="o">:</span> <span class="nx">head</span>
|
||||
<span class="p">};</span>
|
||||
</pre></div> </td> </tr> <tr id="section-68"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-68">¶</a> </div> <p>If the agent for this particular <code>host</code> and <code>port</code> combination
|
||||
is not already listening for the <code>upgrade</code> event, then do so once.
|
||||
This will force us not to disconnect. </p>
|
||||
|
||||
<p>In addition, it's important to note the closure scope here. Since
|
||||
there is no mapping of the </p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">agent</span><span class="p">.</span><span class="nx">_events</span> <span class="o">||</span> <span class="nx">agent</span><span class="p">.</span><span class="nx">_events</span><span class="p">[</span><span class="s1">'upgrade'</span><span class="p">].</span><span class="nx">length</span> <span class="o">===</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">agent</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'upgrade'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">_</span><span class="p">,</span> <span class="nx">remoteSocket</span><span class="p">,</span> <span class="nx">head</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-69"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-69">¶</a> </div> <p>Prepare the socket for the reverseProxy request and begin to
|
||||
stream data between the two sockets. Here it is important to
|
||||
note that <code>remoteSocket._httpMessage === reverseProxy</code>.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">_socket</span><span class="p">(</span><span class="nx">remoteSocket</span><span class="p">,</span> <span class="kc">true</span><span class="p">);</span>
|
||||
<span class="nx">onUpgrade</span><span class="p">(</span><span class="nx">remoteSocket</span><span class="p">.</span><span class="nx">_httpMessage</span><span class="p">,</span> <span class="nx">remoteSocket</span><span class="p">);</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div> </td> </tr> <tr id="section-70"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-70">¶</a> </div> <p>If the reverseProxy connection has an underlying socket,
|
||||
then execute the WebSocket handshake.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">socket</span> <span class="o">!==</span> <span class="s1">'undefined'</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="kd">function</span> <span class="nx">handshake</span> <span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-71"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-71">¶</a> </div> <p>Ok, kind of harmfull part of code. Socket.IO sends a hash
|
||||
at the end of handshake if protocol === 76, but we need
|
||||
to replace 'host' and 'origin' in response so we split
|
||||
data to printable data and to non-printable. (Non-printable
|
||||
will come after double-CRLF).</p> </td> <td class="code"> <div class="highlight"><pre> <span class="kd">var</span> <span class="nx">sdata</span> <span class="o">=</span> <span class="nx">data</span><span class="p">.</span><span class="nx">toString</span><span class="p">();</span></pre></div> </td> </tr> <tr id="section-72"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-72">¶</a> </div> <p>Get the Printable data</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">sdata</span> <span class="o">=</span> <span class="nx">sdata</span><span class="p">.</span><span class="nx">substr</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nx">sdata</span><span class="p">.</span><span class="nx">search</span><span class="p">(</span><span class="nx">CRLF</span> <span class="o">+</span> <span class="nx">CRLF</span><span class="p">));</span></pre></div> </td> </tr> <tr id="section-73"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-73">¶</a> </div> <p>Get the Non-Printable data</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">data</span> <span class="o">=</span> <span class="nx">data</span><span class="p">.</span><span class="nx">slice</span><span class="p">(</span><span class="nx">Buffer</span><span class="p">.</span><span class="nx">byteLength</span><span class="p">(</span><span class="nx">sdata</span><span class="p">),</span> <span class="nx">data</span><span class="p">.</span><span class="nx">length</span><span class="p">);</span>
|
||||
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">self</span><span class="p">.</span><span class="nx">https</span> <span class="o">&&</span> <span class="o">!</span><span class="nx">self</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">https</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-74"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-74">¶</a> </div> <p>If the proxy server is running HTTPS but the client is running
|
||||
HTTP then replace <code>ws</code> with <code>wss</code> in the data sent back to the client.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">sdata</span> <span class="o">=</span> <span class="nx">sdata</span><span class="p">.</span><span class="nx">replace</span><span class="p">(</span><span class="s1">'ws:'</span><span class="p">,</span> <span class="s1">'wss:'</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">try</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-75"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-75">¶</a> </div> <p>Write the printable and non-printable data to the socket
|
||||
from the original incoming request. </p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">self</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'websocket:handshake'</span><span class="p">,</span> <span class="nx">req</span><span class="p">,</span> <span class="nx">socket</span><span class="p">,</span> <span class="nx">head</span><span class="p">,</span> <span class="nx">sdata</span><span class="p">,</span> <span class="nx">data</span><span class="p">);</span>
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">sdata</span><span class="p">);</span>
|
||||
<span class="nx">socket</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">catch</span> <span class="p">(</span><span class="nx">ex</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">proxyError</span><span class="p">(</span><span class="nx">ex</span><span class="p">)</span>
|
||||
<span class="p">}</span></pre></div> </td> </tr> <tr id="section-76"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-76">¶</a> </div> <p>Catch socket errors</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">socket</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'error'</span><span class="p">,</span> <span class="nx">proxyError</span><span class="p">);</span></pre></div> </td> </tr> <tr id="section-77"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-77">¶</a> </div> <p>Remove data listener now that the 'handshake' is complete</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">socket</span><span class="p">.</span><span class="nx">removeListener</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="nx">handshake</span><span class="p">);</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'error'</span><span class="p">,</span> <span class="nx">proxyError</span><span class="p">);</span>
|
||||
|
||||
<span class="k">try</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-78"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-78">¶</a> </div> <p>Attempt to write the upgrade-head to the reverseProxy request.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">reverseProxy</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">head</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">catch</span> <span class="p">(</span><span class="nx">ex</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">proxyError</span><span class="p">(</span><span class="nx">ex</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
</pre></div> </td> </tr> <tr id="section-79"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-79">¶</a> </div> <p>If we have been passed buffered data, resume it.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">buffer</span> <span class="o">&&</span> <span class="o">!</span><span class="nx">errState</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">options</span><span class="p">.</span><span class="nx">buffer</span><span class="p">.</span><span class="nx">resume</span><span class="p">();</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">};</span>
|
||||
|
||||
</pre></div> </td> </tr> </tbody> </table> </div> </body> </html>
|
||||
@ -1,136 +0,0 @@
|
||||
<!DOCTYPE html> <html> <head> <title>proxy-table.js</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" media="all" href="docco.css" /> </head> <body> <div id="container"> <div id="background"></div> <div id="jump_to"> Jump To … <div id="jump_wrapper"> <div id="jump_page"> <a class="source" href="node-http-proxy.html"> node-http-proxy.html </a> <a class="source" href="proxy-table.html"> proxy-table.html </a> </div> </div> </div> <table cellpadding="0" cellspacing="0"> <thead> <tr> <th class="docs"> <h1> proxy-table.js </h1> </th> <th class="code"> </th> </tr> </thead> <tbody> <tr id="section-1"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-1">¶</a> </div> </td> <td class="code"> <div class="highlight"><pre><span class="cm">/*</span>
|
||||
<span class="cm"> node-http-proxy.js: Lookup table for proxy targets in node.js</span>
|
||||
|
||||
<span class="cm"> Copyright (c) 2010 Charlie Robbins </span>
|
||||
|
||||
<span class="cm"> Permission is hereby granted, free of charge, to any person obtaining</span>
|
||||
<span class="cm"> a copy of this software and associated documentation files (the</span>
|
||||
<span class="cm"> "Software"), to deal in the Software without restriction, including</span>
|
||||
<span class="cm"> without limitation the rights to use, copy, modify, merge, publish,</span>
|
||||
<span class="cm"> distribute, sublicense, and/or sell copies of the Software, and to</span>
|
||||
<span class="cm"> permit persons to whom the Software is furnished to do so, subject to</span>
|
||||
<span class="cm"> the following conditions:</span>
|
||||
|
||||
<span class="cm"> The above copyright notice and this permission notice shall be</span>
|
||||
<span class="cm"> included in all copies or substantial portions of the Software.</span>
|
||||
|
||||
<span class="cm"> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,</span>
|
||||
<span class="cm"> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF</span>
|
||||
<span class="cm"> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND</span>
|
||||
<span class="cm"> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE</span>
|
||||
<span class="cm"> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION</span>
|
||||
<span class="cm"> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION</span>
|
||||
<span class="cm"> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</span>
|
||||
|
||||
<span class="cm">*/</span>
|
||||
|
||||
<span class="kd">var</span> <span class="nx">util</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'util'</span><span class="p">),</span>
|
||||
<span class="nx">events</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'events'</span><span class="p">),</span>
|
||||
<span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'fs'</span><span class="p">);</span></pre></div> </td> </tr> <tr id="section-2"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-2">¶</a> </div> <h3>function ProxyTable (router, silent)</h3>
|
||||
|
||||
<h4>@router {Object} Object containing the host based routes</h4>
|
||||
|
||||
<h4>@silent {Boolean} Value indicating whether we should suppress logs</h4>
|
||||
|
||||
<h4>@hostnameOnly {Boolean} Value indicating if we should route based on <strong>hostname string only</strong></h4>
|
||||
|
||||
<p>Constructor function for the ProxyTable responsible for getting
|
||||
locations of proxy targets based on ServerRequest headers; specifically
|
||||
the HTTP host header.</p> </td> <td class="code"> <div class="highlight"><pre><span class="kd">var</span> <span class="nx">ProxyTable</span> <span class="o">=</span> <span class="nx">exports</span><span class="p">.</span><span class="nx">ProxyTable</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">router</span><span class="p">,</span> <span class="nx">silent</span><span class="p">,</span> <span class="nx">hostnameOnly</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">events</span><span class="p">.</span><span class="nx">EventEmitter</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
|
||||
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">silent</span> <span class="o">=</span> <span class="k">typeof</span> <span class="nx">silent</span> <span class="o">!==</span> <span class="s1">'undefined'</span> <span class="o">?</span> <span class="nx">silent</span> <span class="o">:</span> <span class="kc">true</span><span class="p">;</span>
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">hostnameOnly</span> <span class="o">=</span> <span class="k">typeof</span> <span class="nx">hostnameOnly</span> <span class="o">!==</span> <span class="s1">'undefined'</span> <span class="o">?</span> <span class="nx">hostnameOnly</span> <span class="o">:</span> <span class="kc">false</span><span class="p">;</span>
|
||||
|
||||
<span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nx">router</span> <span class="o">===</span> <span class="s1">'object'</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-3"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-3">¶</a> </div> <p>If we are passed an object literal setup
|
||||
the routes with RegExps from the router </p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">this</span><span class="p">.</span><span class="nx">setRoutes</span><span class="p">(</span><span class="nx">router</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nx">router</span> <span class="o">===</span> <span class="s1">'string'</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-4"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-4">¶</a> </div> <p>If we are passed a string then assume it is a
|
||||
file path, parse that file and watch it for changes</p> </td> <td class="code"> <div class="highlight"><pre> <span class="kd">var</span> <span class="nx">self</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span>
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">routeFile</span> <span class="o">=</span> <span class="nx">router</span><span class="p">;</span>
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">setRoutes</span><span class="p">(</span><span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">fs</span><span class="p">.</span><span class="nx">readFileSync</span><span class="p">(</span><span class="nx">router</span><span class="p">)).</span><span class="nx">router</span><span class="p">);</span>
|
||||
|
||||
<span class="nx">fs</span><span class="p">.</span><span class="nx">watchFile</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">routeFile</span><span class="p">,</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
|
||||
<span class="nx">fs</span><span class="p">.</span><span class="nx">readFile</span><span class="p">(</span><span class="nx">self</span><span class="p">.</span><span class="nx">routeFile</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="k">throw</span> <span class="nx">err</span><span class="p">;</span>
|
||||
<span class="nx">self</span><span class="p">.</span><span class="nx">setRoutes</span><span class="p">(</span><span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">data</span><span class="p">).</span><span class="nx">router</span><span class="p">);</span>
|
||||
<span class="nx">self</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'routes'</span><span class="p">,</span> <span class="nx">self</span><span class="p">.</span><span class="nx">hostnameOnly</span> <span class="o">===</span> <span class="kc">false</span> <span class="o">?</span> <span class="nx">self</span><span class="p">.</span><span class="nx">routes</span> <span class="o">:</span> <span class="nx">self</span><span class="p">.</span><span class="nx">router</span><span class="p">);</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">else</span> <span class="p">{</span>
|
||||
<span class="k">throw</span> <span class="k">new</span> <span class="nb">Error</span><span class="p">(</span><span class="s1">'Cannot parse router with unknown type: '</span> <span class="o">+</span> <span class="k">typeof</span> <span class="nx">router</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">};</span></pre></div> </td> </tr> <tr id="section-5"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-5">¶</a> </div> <p>Inherit from events.EventEmitter</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">util</span><span class="p">.</span><span class="nx">inherits</span><span class="p">(</span><span class="nx">ProxyTable</span><span class="p">,</span> <span class="nx">events</span><span class="p">.</span><span class="nx">EventEmitter</span><span class="p">);</span></pre></div> </td> </tr> <tr id="section-6"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-6">¶</a> </div> <h3>function setRoutes (router)</h3>
|
||||
|
||||
<h4>@router {Object} Object containing the host based routes</h4>
|
||||
|
||||
<p>Sets the host-based routes to be used by this instance. </p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">ProxyTable</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">setRoutes</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">router</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">router</span><span class="p">)</span> <span class="k">throw</span> <span class="k">new</span> <span class="nb">Error</span><span class="p">(</span><span class="s1">'Cannot update ProxyTable routes without router.'</span><span class="p">);</span>
|
||||
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">router</span> <span class="o">=</span> <span class="nx">router</span><span class="p">;</span>
|
||||
|
||||
<span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">hostnameOnly</span> <span class="o">===</span> <span class="kc">false</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">self</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span>
|
||||
<span class="k">this</span><span class="p">.</span><span class="nx">routes</span> <span class="o">=</span> <span class="p">[];</span>
|
||||
|
||||
<span class="nb">Object</span><span class="p">.</span><span class="nx">keys</span><span class="p">(</span><span class="nx">router</span><span class="p">).</span><span class="nx">forEach</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">path</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">route</span> <span class="o">=</span> <span class="k">new</span> <span class="nb">RegExp</span><span class="p">(</span><span class="nx">path</span><span class="p">,</span> <span class="s1">'i'</span><span class="p">);</span>
|
||||
|
||||
<span class="nx">self</span><span class="p">.</span><span class="nx">routes</span><span class="p">.</span><span class="nx">push</span><span class="p">({</span>
|
||||
<span class="nx">route</span><span class="o">:</span> <span class="nx">route</span><span class="p">,</span>
|
||||
<span class="nx">target</span><span class="o">:</span> <span class="nx">router</span><span class="p">[</span><span class="nx">path</span><span class="p">]</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">});</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">};</span></pre></div> </td> </tr> <tr id="section-7"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-7">¶</a> </div> <h3>function getProxyLocation (req)</h3>
|
||||
|
||||
<h4>@req {ServerRequest} The incoming server request to get proxy information about.</h4>
|
||||
|
||||
<p>Returns the proxy location based on the HTTP Headers in the ServerRequest <code>req</code>
|
||||
available to this instance.</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">ProxyTable</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">getProxyLocation</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">req</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">req</span> <span class="o">||</span> <span class="o">!</span><span class="nx">req</span><span class="p">.</span><span class="nx">headers</span> <span class="o">||</span> <span class="o">!</span><span class="nx">req</span><span class="p">.</span><span class="nx">headers</span><span class="p">.</span><span class="nx">host</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">return</span> <span class="kc">null</span><span class="p">;</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="kd">var</span> <span class="nx">target</span> <span class="o">=</span> <span class="nx">req</span><span class="p">.</span><span class="nx">headers</span><span class="p">.</span><span class="nx">host</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="s1">':'</span><span class="p">)[</span><span class="mi">0</span><span class="p">];</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">hostnameOnly</span> <span class="o">==</span> <span class="kc">true</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">router</span><span class="p">.</span><span class="nx">hasOwnProperty</span><span class="p">(</span><span class="nx">target</span><span class="p">))</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">location</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">router</span><span class="p">[</span><span class="nx">target</span><span class="p">].</span><span class="nx">split</span><span class="p">(</span><span class="s1">':'</span><span class="p">),</span>
|
||||
<span class="nx">host</span> <span class="o">=</span> <span class="nx">location</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span>
|
||||
<span class="nx">port</span> <span class="o">=</span> <span class="nx">location</span><span class="p">.</span><span class="nx">length</span> <span class="o">===</span> <span class="mi">1</span> <span class="o">?</span> <span class="mi">80</span> <span class="o">:</span> <span class="nx">location</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
|
||||
|
||||
<span class="k">return</span> <span class="p">{</span>
|
||||
<span class="nx">port</span><span class="o">:</span> <span class="nx">port</span><span class="p">,</span>
|
||||
<span class="nx">host</span><span class="o">:</span> <span class="nx">host</span>
|
||||
<span class="p">};</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
<span class="k">else</span> <span class="p">{</span>
|
||||
<span class="nx">target</span> <span class="o">+=</span> <span class="nx">req</span><span class="p">.</span><span class="nx">url</span><span class="p">;</span>
|
||||
<span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="k">in</span> <span class="k">this</span><span class="p">.</span><span class="nx">routes</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">match</span><span class="p">,</span> <span class="nx">route</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">routes</span><span class="p">[</span><span class="nx">i</span><span class="p">];</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="nx">match</span> <span class="o">=</span> <span class="nx">target</span><span class="p">.</span><span class="nx">match</span><span class="p">(</span><span class="nx">route</span><span class="p">.</span><span class="nx">route</span><span class="p">))</span> <span class="p">{</span>
|
||||
<span class="kd">var</span> <span class="nx">location</span> <span class="o">=</span> <span class="nx">route</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="s1">':'</span><span class="p">),</span>
|
||||
<span class="nx">host</span> <span class="o">=</span> <span class="nx">location</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span>
|
||||
<span class="nx">port</span> <span class="o">=</span> <span class="nx">location</span><span class="p">.</span><span class="nx">length</span> <span class="o">===</span> <span class="mi">1</span> <span class="o">?</span> <span class="mi">80</span> <span class="o">:</span> <span class="nx">location</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
|
||||
|
||||
<span class="k">return</span> <span class="p">{</span>
|
||||
<span class="nx">port</span><span class="o">:</span> <span class="nx">port</span><span class="p">,</span>
|
||||
<span class="nx">host</span><span class="o">:</span> <span class="nx">host</span>
|
||||
<span class="p">};</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">}</span>
|
||||
|
||||
<span class="k">return</span> <span class="kc">null</span><span class="p">;</span>
|
||||
<span class="p">};</span></pre></div> </td> </tr> <tr id="section-8"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-8">¶</a> </div> <h3>close function ()</h3>
|
||||
|
||||
<p>Cleans up the event listeneners maintained
|
||||
by this instance.</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">ProxyTable</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">close</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
|
||||
<span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="k">this</span><span class="p">.</span><span class="nx">routeFile</span> <span class="o">===</span> <span class="s1">'string'</span><span class="p">)</span> <span class="p">{</span>
|
||||
<span class="nx">fs</span><span class="p">.</span><span class="nx">unwatchFile</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">routeFile</span><span class="p">);</span>
|
||||
<span class="p">}</span>
|
||||
<span class="p">};</span>
|
||||
|
||||
</pre></div> </td> </tr> </tbody> </table> </div> </body> </html>
|
||||
83
examples/balancer/simple-balancer-with-websockets.js
Normal file
83
examples/balancer/simple-balancer-with-websockets.js
Normal file
@ -0,0 +1,83 @@
|
||||
/*
|
||||
simple-balancer.js: Example of a simple round robin balancer for websockets
|
||||
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
var http = require('http'),
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
//
|
||||
// A simple round-robin load balancing strategy.
|
||||
//
|
||||
// First, list the servers you want to use in your rotation.
|
||||
//
|
||||
var addresses = [
|
||||
{
|
||||
host: 'ws1.0.0.0',
|
||||
port: 80
|
||||
},
|
||||
{
|
||||
host: 'ws2.0.0.0',
|
||||
port: 80
|
||||
}
|
||||
];
|
||||
|
||||
//
|
||||
// Create a HttpProxy object for each target
|
||||
//
|
||||
|
||||
var proxies = addresses.map(function (target) {
|
||||
return new httpProxy.createProxyServer({
|
||||
target: target
|
||||
});
|
||||
});
|
||||
|
||||
//
|
||||
// Get the proxy at the front of the array, put it at the end and return it
|
||||
// If you want a fancier balancer, put your code here
|
||||
//
|
||||
|
||||
function nextProxy() {
|
||||
var proxy = proxies.shift();
|
||||
proxies.push(proxy);
|
||||
return proxy;
|
||||
}
|
||||
|
||||
//
|
||||
// Get the 'next' proxy and send the http request
|
||||
//
|
||||
|
||||
var server = http.createServer(function (req, res) {
|
||||
nextProxy().web(req, res);
|
||||
});
|
||||
|
||||
//
|
||||
// Get the 'next' proxy and send the upgrade request
|
||||
//
|
||||
|
||||
server.on('upgrade', function (req, socket, head) {
|
||||
nextProxy().ws(req, socket, head);
|
||||
});
|
||||
|
||||
server.listen(8001);
|
||||
64
examples/balancer/simple-balancer.js
Normal file
64
examples/balancer/simple-balancer.js
Normal file
@ -0,0 +1,64 @@
|
||||
/*
|
||||
simple-balancer.js: Example of a simple round robin balancer
|
||||
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
var http = require('http'),
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
//
|
||||
// A simple round-robin load balancing strategy.
|
||||
//
|
||||
// First, list the servers you want to use in your rotation.
|
||||
//
|
||||
var addresses = [
|
||||
{
|
||||
host: 'ws1.0.0.0',
|
||||
port: 80
|
||||
},
|
||||
{
|
||||
host: 'ws2.0.0.0',
|
||||
port: 80
|
||||
}
|
||||
];
|
||||
var proxy = httpProxy.createServer();
|
||||
|
||||
http.createServer(function (req, res) {
|
||||
//
|
||||
// On each request, get the first location from the list...
|
||||
//
|
||||
var target = { target: addresses.shift() };
|
||||
|
||||
//
|
||||
// ...then proxy to the server whose 'turn' it is...
|
||||
//
|
||||
console.log('balancing request to: ', target);
|
||||
proxy.web(req, res, target);
|
||||
|
||||
//
|
||||
// ...and then the server you just used becomes the last item in the list.
|
||||
//
|
||||
addresses.push(target.target);
|
||||
}).listen(8021);
|
||||
|
||||
// Rinse; repeat; enjoy.
|
||||
@ -2,7 +2,7 @@
|
||||
//
|
||||
// just to make these example a little bit interesting,
|
||||
// make a little key value store with an http interface
|
||||
// (see couchbd for a grown-up version of this)
|
||||
// (see couchdb for a grown-up version of this)
|
||||
//
|
||||
// API:
|
||||
// GET /
|
||||
@ -39,10 +39,10 @@ Store.prototype = {
|
||||
res.end()
|
||||
}
|
||||
var url = req.url.split('?').shift()
|
||||
if(url === '/') {
|
||||
if (url === '/') {
|
||||
console.log('get index')
|
||||
return send(Object.keys(store.store))
|
||||
} else if(req.method == 'GET') {
|
||||
} else if (req.method == 'GET') {
|
||||
var obj = store.get (url)
|
||||
send(obj || {error: 'not_found', url: url}, obj ? 200 : 404)
|
||||
} else {
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
basic-proxy.js: Basic example of proxying over HTTP
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -27,14 +27,14 @@
|
||||
var util = require('util'),
|
||||
colors = require('colors'),
|
||||
http = require('http'),
|
||||
httpProxy = require('../../lib/node-http-proxy');
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
var welcome = [
|
||||
'# # ##### ##### ##### ##### ##### #### # # # #',
|
||||
'# # # # # # # # # # # # # # # # ',
|
||||
'###### # # # # ##### # # # # # # ## # ',
|
||||
'# # # # ##### ##### ##### # # ## # ',
|
||||
'# # # # # # # # # # # # # ',
|
||||
'# # # # # # # # # # # # # # # # ',
|
||||
'###### # # # # ##### # # # # # # ## # ',
|
||||
'# # # # ##### ##### ##### # # ## # ',
|
||||
'# # # # # # # # # # # # # ',
|
||||
'# # # # # # # # #### # # # '
|
||||
].join('\n');
|
||||
|
||||
@ -43,7 +43,9 @@ util.puts(welcome.rainbow.bold);
|
||||
//
|
||||
// Basic Http Proxy Server
|
||||
//
|
||||
httpProxy.createServer(9000, 'localhost').listen(8000);
|
||||
httpProxy.createServer({
|
||||
target:'http://localhost:9003'
|
||||
}).listen(8003);
|
||||
|
||||
//
|
||||
// Target Http Server
|
||||
@ -52,7 +54,7 @@ http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9000);
|
||||
}).listen(9003);
|
||||
|
||||
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
|
||||
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8003'.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9003 '.yellow);
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
concurrent-proxy.js: check levelof concurrency through proxy.
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -27,12 +27,14 @@
|
||||
var util = require('util'),
|
||||
colors = require('colors'),
|
||||
http = require('http'),
|
||||
httpProxy = require('../../lib/node-http-proxy');
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
//
|
||||
// Basic Http Proxy Server
|
||||
//
|
||||
httpProxy.createServer(9000, 'localhost').listen(8000);
|
||||
httpProxy.createServer({
|
||||
target:'http://localhost:9004'
|
||||
}).listen(8004);
|
||||
|
||||
//
|
||||
// Target Http Server
|
||||
@ -42,7 +44,7 @@ httpProxy.createServer(9000, 'localhost').listen(8000);
|
||||
//
|
||||
|
||||
|
||||
var connections = [],
|
||||
var connections = [],
|
||||
go;
|
||||
|
||||
http.createServer(function (req, res) {
|
||||
@ -51,16 +53,16 @@ http.createServer(function (req, res) {
|
||||
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
});
|
||||
|
||||
|
||||
process.stdout.write(connections.length + ', ');
|
||||
|
||||
|
||||
if (connections.length > 110 || go) {
|
||||
go = true;
|
||||
while (connections.length) {
|
||||
connections.shift()();
|
||||
}
|
||||
}
|
||||
}).listen(9000);
|
||||
}).listen(9004);
|
||||
|
||||
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
|
||||
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8004'.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9004 '.yellow);
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
custom-proxy-error.js: Example of using the custom `proxyError` event.
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -27,28 +27,29 @@
|
||||
var util = require('util'),
|
||||
colors = require('colors'),
|
||||
http = require('http'),
|
||||
httpProxy = require('../../lib/node-http-proxy');
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
//
|
||||
// Http Proxy Server with Latency
|
||||
// Http Proxy Server with bad target
|
||||
//
|
||||
var server = httpProxy.createServer(9000, 'localhost');
|
||||
var proxy = httpProxy.createServer({
|
||||
target:'http://localhost:9005'
|
||||
});
|
||||
|
||||
//
|
||||
// Tell the server to listen on port 8002
|
||||
// Tell the proxy to listen on port 8000
|
||||
//
|
||||
server.listen(8002);
|
||||
proxy.listen(8005);
|
||||
|
||||
//
|
||||
// Listen for the `proxyError` event on `server.proxy`. _It will not
|
||||
// be raised on the server itself._
|
||||
server.proxy.on('proxyError', function (err, req, res) {
|
||||
// Listen for the `error` event on `proxy`.
|
||||
proxy.on('error', function (err, req, res) {
|
||||
res.writeHead(500, {
|
||||
'Content-Type': 'text/plain'
|
||||
});
|
||||
|
||||
|
||||
res.end('Something went wrong. And we are reporting a custom error message.');
|
||||
});
|
||||
|
||||
|
||||
util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8002 '.yellow + 'with custom error message'.magenta.underline);
|
||||
util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8005 '.yellow + 'with custom error message'.magenta.underline);
|
||||
63
examples/http/error-handling.js
Normal file
63
examples/http/error-handling.js
Normal file
@ -0,0 +1,63 @@
|
||||
/*
|
||||
error-handling.js: Example of handle erros for HTTP and WebSockets
|
||||
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
var util = require('util'),
|
||||
colors = require('colors'),
|
||||
http = require('http'),
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
//
|
||||
// HTTP Proxy Server
|
||||
//
|
||||
var proxy = httpProxy.createProxyServer({target:'http://localhost:9000', ws:true});
|
||||
|
||||
//
|
||||
// Example of error handling
|
||||
//
|
||||
function requestHandler(req, res) {
|
||||
// Pass a callback to the web proxy method
|
||||
// and catch the error there.
|
||||
proxy.web(req, res, function (err) {
|
||||
// Now you can get the err
|
||||
// and handle it by your self
|
||||
// if (err) throw err;
|
||||
res.writeHead(502);
|
||||
res.end("There was an error proxying your request");
|
||||
});
|
||||
|
||||
// In a websocket request case
|
||||
req.on('upgrade', function (req, socket, head) {
|
||||
proxy.ws(req, socket, head, function (err) {
|
||||
// Now you can get the err
|
||||
// and handle it by your self
|
||||
// if (err) throw err;
|
||||
socket.close();
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
http.createServer(requestHandler).listen(8000);
|
||||
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
|
||||
67
examples/http/forward-and-target-proxy.js
Normal file
67
examples/http/forward-and-target-proxy.js
Normal file
@ -0,0 +1,67 @@
|
||||
/*
|
||||
forward-and-target-proxy.js: Example of proxying over HTTP with additional forward proxy
|
||||
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
var util = require('util'),
|
||||
colors = require('colors'),
|
||||
http = require('http'),
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
//
|
||||
// Setup proxy server with forwarding
|
||||
//
|
||||
httpProxy.createServer({
|
||||
target: {
|
||||
port: 9006,
|
||||
host: 'localhost'
|
||||
},
|
||||
forward: {
|
||||
port: 9007,
|
||||
host: 'localhost'
|
||||
}
|
||||
}).listen(8006);
|
||||
|
||||
//
|
||||
// Target Http Server
|
||||
//
|
||||
http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9006);
|
||||
|
||||
//
|
||||
// Target Http Forwarding Server
|
||||
//
|
||||
http.createServer(function (req, res) {
|
||||
util.puts('Receiving forward for: ' + req.url);
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully forwarded to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9007);
|
||||
|
||||
util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8006 '.yellow + 'with forward proxy'.magenta.underline);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9006 '.yellow);
|
||||
util.puts('http forward server '.blue + 'started '.green.bold + 'on port '.blue + '9007 '.yellow);
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
forward-proxy.js: Example of proxying over HTTP with additional forward proxy
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -27,26 +27,17 @@
|
||||
var util = require('util'),
|
||||
colors = require('colors'),
|
||||
http = require('http'),
|
||||
httpProxy = require('../../lib/node-http-proxy');
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
//
|
||||
// Setup proxy server with forwarding
|
||||
//
|
||||
httpProxy.createServer(9000, 'localhost', {
|
||||
httpProxy.createServer({
|
||||
forward: {
|
||||
port: 9001,
|
||||
port: 9019,
|
||||
host: 'localhost'
|
||||
}
|
||||
}).listen(8003);
|
||||
|
||||
//
|
||||
// Target Http Server
|
||||
//
|
||||
http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9000);
|
||||
}).listen(8019);
|
||||
|
||||
//
|
||||
// Target Http Forwarding Server
|
||||
@ -56,8 +47,7 @@ http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully forwarded to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9001);
|
||||
}).listen(9019);
|
||||
|
||||
util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8003 '.yellow + 'with forward proxy'.magenta.underline);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
|
||||
util.puts('http forward server '.blue + 'started '.green.bold + 'on port '.blue + '9001 '.yellow);
|
||||
util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8019 '.yellow + 'with forward proxy'.magenta.underline);
|
||||
util.puts('http forward server '.blue + 'started '.green.bold + 'on port '.blue + '9019 '.yellow);
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
latent-proxy.js: Example of proxying over HTTP with latency
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -27,21 +27,19 @@
|
||||
var util = require('util'),
|
||||
colors = require('colors'),
|
||||
http = require('http'),
|
||||
httpProxy = require('../../lib/node-http-proxy');
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
//
|
||||
// Http Proxy Server with Latency
|
||||
//
|
||||
httpProxy.createServer(function (req, res, proxy) {
|
||||
var buffer = httpProxy.buffer(req);
|
||||
setTimeout(function() {
|
||||
proxy.proxyRequest(req, res, {
|
||||
port: 9000,
|
||||
host: 'localhost',
|
||||
buffer: buffer
|
||||
var proxy = httpProxy.createProxyServer();
|
||||
http.createServer(function (req, res) {
|
||||
setTimeout(function () {
|
||||
proxy.web(req, res, {
|
||||
target: 'http://localhost:9008'
|
||||
});
|
||||
}, 200);
|
||||
}).listen(8002);
|
||||
}, 500);
|
||||
}).listen(8008);
|
||||
|
||||
//
|
||||
// Target Http Server
|
||||
@ -50,7 +48,7 @@ http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9000);
|
||||
}).listen(9008);
|
||||
|
||||
util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8002 '.yellow + 'with latency'.magenta.underline);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
|
||||
util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8008 '.yellow + 'with latency'.magenta.underline);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9008 '.yellow);
|
||||
|
||||
26
examples/http/ntlm-authentication.js
Normal file
26
examples/http/ntlm-authentication.js
Normal file
@ -0,0 +1,26 @@
|
||||
var httpProxy = require('../../lib/http-proxy');
|
||||
var Agent = require('agentkeepalive');
|
||||
|
||||
var agent = new Agent({
|
||||
maxSockets: 100,
|
||||
keepAlive: true,
|
||||
maxFreeSockets: 10,
|
||||
keepAliveMsecs:1000,
|
||||
timeout: 60000,
|
||||
keepAliveTimeout: 30000 // free socket keepalive for 30 seconds
|
||||
});
|
||||
|
||||
var proxy = httpProxy.createProxy({ target: 'http://whatever.com', agent: agent });
|
||||
|
||||
//
|
||||
// Modify headers of the response before it gets sent
|
||||
// So that we handle the NLTM authentication response
|
||||
//
|
||||
proxy.on('proxyRes', function (proxyRes) {
|
||||
var key = 'www-authenticate';
|
||||
proxyRes.headers[key] = proxyRes.headers[key] && proxyRes.headers[key].split(',');
|
||||
});
|
||||
|
||||
require('http').createServer(function (req, res) {
|
||||
proxy.web(req, res);
|
||||
}).listen(3000);
|
||||
46
examples/http/proxy-http-to-https.js
Normal file
46
examples/http/proxy-http-to-https.js
Normal file
@ -0,0 +1,46 @@
|
||||
/*
|
||||
proxy-http-to-https.js: Basic example of proxying over HTTP to a target HTTPS server
|
||||
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
var https = require('https'),
|
||||
http = require('http'),
|
||||
util = require('util'),
|
||||
path = require('path'),
|
||||
fs = require('fs'),
|
||||
colors = require('colors'),
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
//
|
||||
// Create a HTTP Proxy server with a HTTPS target
|
||||
//
|
||||
httpProxy.createProxyServer({
|
||||
target: 'https://google.com',
|
||||
agent : https.globalAgent,
|
||||
headers: {
|
||||
host: 'google.com'
|
||||
}
|
||||
}).listen(8011);
|
||||
|
||||
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8011'.yellow);
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
proxy-https-to-http.js: Basic example of proxying over HTTPS to a target HTTP server
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -25,29 +25,36 @@
|
||||
*/
|
||||
|
||||
var https = require('https'),
|
||||
http = require('http'),
|
||||
util = require('util'),
|
||||
http = require('http'),
|
||||
util = require('util'),
|
||||
path = require('path'),
|
||||
fs = require('fs'),
|
||||
colors = require('colors'),
|
||||
httpProxy = require('../../lib/node-http-proxy'),
|
||||
helpers = require('../../test/helpers');
|
||||
|
||||
var opts = helpers.loadHttps();
|
||||
httpProxy = require('../../lib/http-proxy'),
|
||||
fixturesDir = path.join(__dirname, '..', '..', 'test', 'fixtures');
|
||||
|
||||
//
|
||||
// Crete the target HTTPS server
|
||||
// Create the target HTTP server
|
||||
//
|
||||
http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('hello http over https\n');
|
||||
res.end();
|
||||
}).listen(8000);
|
||||
res.end();
|
||||
}).listen(9009);
|
||||
|
||||
//
|
||||
// Create the proxy server listening on port 443.
|
||||
// Create the HTTPS proxy server listening on port 8000
|
||||
//
|
||||
httpProxy.createServer(8000, 'localhost', {
|
||||
https: opts
|
||||
}).listen(8080);
|
||||
httpProxy.createServer({
|
||||
target: {
|
||||
host: 'localhost',
|
||||
port: 9009
|
||||
},
|
||||
ssl: {
|
||||
key: fs.readFileSync(path.join(fixturesDir, 'agent2-key.pem'), 'utf8'),
|
||||
cert: fs.readFileSync(path.join(fixturesDir, 'agent2-cert.pem'), 'utf8')
|
||||
}
|
||||
}).listen(8009);
|
||||
|
||||
util.puts('https proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8080'.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '8000 '.yellow);
|
||||
util.puts('https proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8009'.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9009 '.yellow);
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
proxy-https-to-https.js: Basic example of proxying over HTTPS to a target HTTPS server
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -27,30 +27,33 @@
|
||||
var https = require('https'),
|
||||
http = require('http'),
|
||||
util = require('util'),
|
||||
fs = require('fs'),
|
||||
path = require('path'),
|
||||
colors = require('colors'),
|
||||
httpProxy = require('../../lib/node-http-proxy'),
|
||||
helpers = require('../../test/helpers');
|
||||
|
||||
var opts = helpers.loadHttps();
|
||||
httpProxy = require('../../lib/http-proxy'),
|
||||
fixturesDir = path.join(__dirname, '..', '..', 'test', 'fixtures'),
|
||||
httpsOpts = {
|
||||
key: fs.readFileSync(path.join(fixturesDir, 'agent2-key.pem'), 'utf8'),
|
||||
cert: fs.readFileSync(path.join(fixturesDir, 'agent2-cert.pem'), 'utf8')
|
||||
};
|
||||
|
||||
//
|
||||
// Crete the target HTTPS server
|
||||
// Create the target HTTPS server
|
||||
//
|
||||
https.createServer(opts, function (req, res) {
|
||||
https.createServer(httpsOpts, function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('hello https\n');
|
||||
res.end();
|
||||
}).listen(8000);
|
||||
res.end();
|
||||
}).listen(9010);
|
||||
|
||||
//
|
||||
// Create the proxy server listening on port 443.
|
||||
// Create the proxy server listening on port 8010
|
||||
//
|
||||
httpProxy.createServer(8000, 'localhost', {
|
||||
https: opts,
|
||||
target: {
|
||||
https: true
|
||||
}
|
||||
}).listen(8080);
|
||||
httpProxy.createServer({
|
||||
ssl: httpsOpts,
|
||||
target: 'https://localhost:9010',
|
||||
secure: false
|
||||
}).listen(8010);
|
||||
|
||||
util.puts('https proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8080'.yellow);
|
||||
util.puts('https server '.blue + 'started '.green.bold + 'on port '.blue + '8000 '.yellow);
|
||||
util.puts('https proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8010'.yellow);
|
||||
util.puts('https server '.blue + 'started '.green.bold + 'on port '.blue + '9010 '.yellow);
|
||||
|
||||
55
examples/http/reverse-proxy.js
Normal file
55
examples/http/reverse-proxy.js
Normal file
@ -0,0 +1,55 @@
|
||||
/*
|
||||
reverse-proxy.js: Example of reverse proxying (with HTTPS support)
|
||||
Copyright (c) 2015 Alberto Pose <albertopose@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
var http = require('http'),
|
||||
net = require('net'),
|
||||
httpProxy = require('../../lib/http-proxy'),
|
||||
url = require('url'),
|
||||
util = require('util');
|
||||
|
||||
var proxy = httpProxy.createServer();
|
||||
|
||||
var server = http.createServer(function (req, res) {
|
||||
util.puts('Receiving reverse proxy request for:' + req.url);
|
||||
var parsedUrl = url.parse(req.url);
|
||||
var target = parsedUrl.protocol + '//' + parsedUrl.hostname;
|
||||
proxy.web(req, res, {target: target, secure: false});
|
||||
}).listen(8213);
|
||||
|
||||
server.on('connect', function (req, socket) {
|
||||
util.puts('Receiving reverse proxy request for:' + req.url);
|
||||
|
||||
var serverUrl = url.parse('https://' + req.url);
|
||||
|
||||
var srvSocket = net.connect(serverUrl.port, serverUrl.hostname, function() {
|
||||
socket.write('HTTP/1.1 200 Connection Established\r\n' +
|
||||
'Proxy-agent: Node-Proxy\r\n' +
|
||||
'\r\n');
|
||||
srvSocket.pipe(socket);
|
||||
socket.pipe(srvSocket);
|
||||
});
|
||||
});
|
||||
|
||||
// Test with:
|
||||
// curl -vv -x http://127.0.0.1:8213 https://www.google.com
|
||||
// curl -vv -x http://127.0.0.1:8213 http://www.google.com
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
proxy-table.js: Example of proxying over HTTP with proxy table
|
||||
sse.js: Basic example of proxying over HTTP
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -27,25 +27,41 @@
|
||||
var util = require('util'),
|
||||
colors = require('colors'),
|
||||
http = require('http'),
|
||||
httpProxy = require('../../lib/node-http-proxy');
|
||||
httpProxy = require('../../lib/http-proxy'),
|
||||
SSE = require('sse');
|
||||
|
||||
//
|
||||
// Http Proxy Server with Proxy Table
|
||||
// Basic Http Proxy Server
|
||||
//
|
||||
httpProxy.createServer({
|
||||
router: {
|
||||
'localhost': 'localhost:9000'
|
||||
}
|
||||
}).listen(8001);
|
||||
var proxy = new httpProxy.createProxyServer();
|
||||
http.createServer(function (req, res) {
|
||||
proxy.web(req, res, {
|
||||
target: 'http://localhost:9003'
|
||||
});
|
||||
}).listen(8003);
|
||||
|
||||
//
|
||||
// Target Http Server
|
||||
//
|
||||
http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
var server = http.createServer(function(req, res) {
|
||||
res.writeHead(200, {'Content-Type': 'text/html'});
|
||||
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9000);
|
||||
});
|
||||
|
||||
util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8001 '.yellow + 'with proxy table'.magenta.underline);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
|
||||
//
|
||||
// Use SSE
|
||||
//
|
||||
|
||||
var sse = new SSE(server, {path: '/'});
|
||||
sse.on('connection', function(client) {
|
||||
var count = 0;
|
||||
setInterval(function(){
|
||||
client.send('message #' + count++);
|
||||
}, 1500);
|
||||
});
|
||||
|
||||
server.listen(9003);
|
||||
|
||||
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8003'.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9003 '.yellow);
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
standalone-proxy.js: Example of proxying over HTTP with a standalone HTTP server.
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -27,22 +27,19 @@
|
||||
var util = require('util'),
|
||||
colors = require('colors'),
|
||||
http = require('http'),
|
||||
httpProxy = require('../../lib/node-http-proxy');
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
//
|
||||
// Http Server with proxyRequest Handler and Latency
|
||||
//
|
||||
var proxy = new httpProxy.RoutingProxy();
|
||||
var proxy = new httpProxy.createProxyServer();
|
||||
http.createServer(function (req, res) {
|
||||
var buffer = httpProxy.buffer(req);
|
||||
setTimeout(function() {
|
||||
proxy.proxyRequest(req, res, {
|
||||
port: 9000,
|
||||
host: 'localhost',
|
||||
buffer: buffer
|
||||
setTimeout(function () {
|
||||
proxy.web(req, res, {
|
||||
target: 'http://localhost:9002'
|
||||
});
|
||||
}, 200);
|
||||
}).listen(8004);
|
||||
}).listen(8002);
|
||||
|
||||
//
|
||||
// Target Http Server
|
||||
@ -51,7 +48,7 @@ http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9000);
|
||||
}).listen(9002);
|
||||
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '8004 '.yellow + 'with proxyRequest handler'.cyan.underline + ' and latency'.magenta);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '8002 '.yellow + 'with proxy.web() handler'.cyan.underline + ' and latency'.magenta);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9002 '.yellow);
|
||||
|
||||
@ -1,87 +1,108 @@
|
||||
/*
|
||||
bodyDecoder-middleware.js: Basic example of `connect.bodyParser()` middleware in node-http-proxy
|
||||
|
||||
var Store = require('../helpers/store')
|
||||
, http = require('http')
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
var http = require('http'),
|
||||
connect = require('connect'),
|
||||
request = require('request'),
|
||||
colors = require('colors'),
|
||||
util = require('util'),
|
||||
queryString = require('querystring'),
|
||||
bodyParser = require('body-parser'),
|
||||
httpProxy = require('../../lib/http-proxy'),
|
||||
proxy = httpProxy.createProxyServer({});
|
||||
|
||||
|
||||
//restream parsed body before proxying
|
||||
proxy.on('proxyReq', function(proxyReq, req, res, options) {
|
||||
if (!req.body || !Object.keys(req.body).length) {
|
||||
return;
|
||||
}
|
||||
|
||||
var contentType = proxyReq.getHeader('Content-Type');
|
||||
var bodyData;
|
||||
|
||||
if (contentType === 'application/json') {
|
||||
bodyData = JSON.stringify(req.body);
|
||||
}
|
||||
|
||||
if (contentType === 'application/x-www-form-urlencoded') {
|
||||
bodyData = queryString.stringify(req.body);
|
||||
}
|
||||
|
||||
if (bodyData) {
|
||||
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
|
||||
proxyReq.write(bodyData);
|
||||
}
|
||||
});
|
||||
|
||||
http.createServer(new Store().handler()).listen(7531, function () {
|
||||
//try these commands:
|
||||
// get index:
|
||||
// curl localhost:7531
|
||||
// []
|
||||
//
|
||||
// get a doc:
|
||||
// curl localhost:7531/foo
|
||||
// {"error":"not_found"}
|
||||
//
|
||||
// post an doc:
|
||||
// curl -X POST localhost:7531/foo -d '{"content": "hello", "type": "greeting"}'
|
||||
// {"ok":true}
|
||||
//
|
||||
// get index (now, not empty)
|
||||
// curl localhost:7531
|
||||
// ["/foo"]
|
||||
//
|
||||
// get doc
|
||||
// curl localhost:7531/foo
|
||||
// {"content": "hello", "type": "greeting"}
|
||||
|
||||
//
|
||||
// now, suppose we wanted to direct all objects where type == "greeting" to a different store
|
||||
// than where type == "insult"
|
||||
// Basic Http Proxy Server
|
||||
//
|
||||
// we can use connect connect-bodyDecoder and some custom logic to send insults to another Store.
|
||||
|
||||
//insult server:
|
||||
|
||||
http.createServer(new Store().handler()).listen(2600, function () {
|
||||
|
||||
//greetings -> 7531, insults-> 2600
|
||||
|
||||
// now, start a proxy server.
|
||||
|
||||
var bodyParser = require('connect/lib/middleware/bodyParser')
|
||||
//don't worry about incoming contont type
|
||||
//bodyParser.parse[''] = JSON.parse
|
||||
|
||||
require('../../lib/node-http-proxy').createServer(
|
||||
//refactor the body parser and re-streamer into a separate package
|
||||
bodyParser(),
|
||||
//body parser absorbs the data and end events before passing control to the next
|
||||
// middleware. if we want to proxy it, we'll need to re-emit these events after
|
||||
//passing control to the middleware.
|
||||
require('connect-restreamer')(),
|
||||
function (req, res, proxy) {
|
||||
//if your posting an obect which contains type: "insult"
|
||||
//it will get redirected to port 2600.
|
||||
//normal get requests will go to 7531 nad will not return insults.
|
||||
var port = (req.body && req.body.type === 'insult' ? 2600 : 7531)
|
||||
proxy.proxyRequest(req, res, {host: 'localhost', port: port})
|
||||
}
|
||||
).listen(1337, function () {
|
||||
var request = require('request')
|
||||
//bodyParser needs content-type set to application/json
|
||||
//if we use request, it will set automatically if we use the 'json:' field.
|
||||
function post (greeting, type) {
|
||||
request.post({
|
||||
url: 'http://localhost:1337/' + greeting,
|
||||
json: {content: greeting, type: type || "greeting"}
|
||||
})
|
||||
}
|
||||
post("hello")
|
||||
post("g'day")
|
||||
post("kiora")
|
||||
post("houdy")
|
||||
post("java", "insult")
|
||||
|
||||
//now, the insult should have been proxied to 2600
|
||||
|
||||
//curl localhost:2600
|
||||
//["/java"]
|
||||
|
||||
//but the greetings will be sent to 7531
|
||||
|
||||
//curl localhost:7531
|
||||
//["/hello","/g%27day","/kiora","/houdy"]
|
||||
|
||||
var app = connect()
|
||||
.use(bodyParser.json())//json parser
|
||||
.use(bodyParser.urlencoded())//urlencoded parser
|
||||
.use(function(req, res){
|
||||
// modify body here,
|
||||
// eg: req.body = {a: 1}.
|
||||
console.log('proxy body:',req.body)
|
||||
proxy.web(req, res, {
|
||||
target: 'http://127.0.0.1:9013'
|
||||
})
|
||||
});
|
||||
|
||||
http.createServer(app).listen(8013, function(){
|
||||
console.log('proxy linsten 8013');
|
||||
});
|
||||
|
||||
|
||||
|
||||
//
|
||||
// Target Http Server
|
||||
//
|
||||
var app1 = connect()
|
||||
.use(bodyParser.json())
|
||||
.use(function(req, res){
|
||||
console.log('app1:',req.body)
|
||||
res.end('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
});
|
||||
http.createServer(app1).listen(9013, function(){
|
||||
//request to 8013 to proxy
|
||||
request.post({//
|
||||
url: 'http://127.0.0.1:8013',
|
||||
json: {content: 123, type: "greeting from json request"}
|
||||
},function(err, res,data){
|
||||
console.log('return for json request:' ,err, data)
|
||||
})
|
||||
})
|
||||
|
||||
// application/x-www-form-urlencoded request
|
||||
request.post({//
|
||||
url: 'http://127.0.0.1:8013',
|
||||
form: {content: 123, type: "greeting from urlencoded request"}
|
||||
},function(err, res,data){
|
||||
console.log('return for urlencoded request:' ,err, data)
|
||||
})
|
||||
});
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
gzip-middleware.js: Basic example of `connect-gzip` middleware in node-http-proxy
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, Marak Squires, & Dominic Tarr.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -27,15 +27,30 @@
|
||||
var util = require('util'),
|
||||
colors = require('colors'),
|
||||
http = require('http'),
|
||||
httpProxy = require('../../lib/node-http-proxy');
|
||||
connect = require('connect'),
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
//
|
||||
// Basic Connect App
|
||||
//
|
||||
connect.createServer(
|
||||
connect.compress({
|
||||
// Pass to connect.compress() the options
|
||||
// that you need, just for show the example
|
||||
// we use threshold to 1
|
||||
threshold: 1
|
||||
}),
|
||||
function (req, res) {
|
||||
proxy.web(req, res);
|
||||
}
|
||||
).listen(8012);
|
||||
|
||||
//
|
||||
// Basic Http Proxy Server
|
||||
//
|
||||
httpProxy.createServer(
|
||||
require('connect-gzip').gzip({ matchType: /.?/ }),
|
||||
9000, 'localhost'
|
||||
).listen(8000);
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://localhost:9012'
|
||||
});
|
||||
|
||||
//
|
||||
// Target Http Server
|
||||
@ -44,7 +59,7 @@ http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9000);
|
||||
}).listen(9012);
|
||||
|
||||
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
|
||||
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8012'.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9012 '.yellow);
|
||||
|
||||
@ -1,30 +0,0 @@
|
||||
var Store = require('../helpers/store')
|
||||
, http = require('http')
|
||||
|
||||
//
|
||||
// jsonp is a handy technique for getting around the limitations of the same-origin policy.
|
||||
// (http://en.wikipedia.org/wiki/Same_origin_policy)
|
||||
//
|
||||
// normally, to dynamically update a page you use an XmlHttpRequest. this has flakey support
|
||||
// is some browsers and is restricted by the same origin policy. you cannot perform XHR requests to
|
||||
// someone else's server. one way around this would be to proxy requests to all the servers you want
|
||||
// to xhr to, and your core server - so that everything has the same port and host.
|
||||
//
|
||||
// another way, is to turn json into javascript. (which is exempt from the same origin policy)
|
||||
// this is done by wrapping the json object in a function call, and then including a script tag.
|
||||
//
|
||||
// here we're proxing our own JSON returning server, but we could proxy any server on the internet,
|
||||
// and our client side app would be slurping down JSONP from anywhere.
|
||||
//
|
||||
// curl localhost:1337/whatever?callback=alert
|
||||
// alert([]) //which is valid javascript!
|
||||
//
|
||||
// also see http://en.wikipedia.org/wiki/JSONP#JSONP
|
||||
//
|
||||
|
||||
http.createServer(new Store().handler()).listen(7531)
|
||||
|
||||
require('../../lib/node-http-proxy').createServer(
|
||||
require('connect-jsonp')(true),
|
||||
'localhost', 7531
|
||||
).listen(1337)
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
url-middleware.js: Example of a simple url routing middleware for node-http-proxy
|
||||
modifyBody-middleware.js: Example of middleware which modifies response
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -27,32 +27,43 @@
|
||||
var util = require('util'),
|
||||
colors = require('colors'),
|
||||
http = require('http'),
|
||||
httpProxy = require('../../lib/node-http-proxy');
|
||||
connect = require('connect'),
|
||||
app = connect(),
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
//
|
||||
// Now we set up our proxy.
|
||||
// Basic Connect App
|
||||
//
|
||||
httpProxy.createServer(
|
||||
//
|
||||
// This is where our middlewares go, with any options desired - in this case,
|
||||
// the list of routes/URLs and their destinations.
|
||||
//
|
||||
require('proxy-by-url')({
|
||||
'/hello': { port: 9000, host: 'localhost' },
|
||||
'/charlie': { port: 80, host: 'charlieistheman.com' },
|
||||
'/google': { port: 80, host: 'google.com' }
|
||||
})
|
||||
).listen(8000);
|
||||
app.use(function (req, res, next) {
|
||||
var _write = res.write;
|
||||
|
||||
res.write = function (data) {
|
||||
_write.call(res, data.toString().replace("Ruby", "http-party"));
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
app.use(function (req, res) {
|
||||
proxy.web(req, res)
|
||||
});
|
||||
|
||||
http.createServer(app).listen(8013);
|
||||
|
||||
//
|
||||
// Target Http Server (to listen for requests on 'localhost')
|
||||
// Basic Http Proxy Server
|
||||
//
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://localhost:9013'
|
||||
});
|
||||
|
||||
//
|
||||
// Target Http Server
|
||||
//
|
||||
http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9000);
|
||||
res.end('Hello, I love Ruby\n');
|
||||
}).listen(9013);
|
||||
|
||||
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8013'.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9013 '.yellow);
|
||||
|
||||
// And finally, some colored startup output.
|
||||
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
|
||||
@ -1,30 +0,0 @@
|
||||
var util = require('util'),
|
||||
colors = require('colors'),
|
||||
http = require('http'),
|
||||
httpProxy = require('../../lib/node-http-proxy'),
|
||||
Store = require('../helpers/store')
|
||||
|
||||
http.createServer(new Store().handler()).listen(7531)
|
||||
|
||||
// Now we set up our proxy.
|
||||
httpProxy.createServer(
|
||||
// This is where our middlewares go, with any options desired - in this case,
|
||||
// the list of routes/URLs and their destinations.
|
||||
require('proxy-by-url')({
|
||||
'/store': { port: 7531, host: 'localhost' },
|
||||
'/': { port: 9000, host: 'localhost' }
|
||||
})
|
||||
).listen(8000);
|
||||
|
||||
//
|
||||
// Target Http Server (to listen for requests on 'localhost')
|
||||
//
|
||||
http.createServer(function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
|
||||
res.end();
|
||||
}).listen(9000);
|
||||
|
||||
// And finally, some colored startup output.
|
||||
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
|
||||
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
|
||||
@ -1,12 +1,14 @@
|
||||
{
|
||||
"name": "http-proxy-examples",
|
||||
"description": "packages required to run the examples",
|
||||
"name": "http-proxy-examples",
|
||||
"description": "packages required to run the examples",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"connect": "1.6",
|
||||
"connect-gzip": "0.1",
|
||||
"connect-jsonp": "0.0.5",
|
||||
"connect-restreamer": "1",
|
||||
"proxy-by-url": ">= 0.0.1"
|
||||
"agentkeepalive": "^4.0.0",
|
||||
"colors": "~1.3.0",
|
||||
"connect-restreamer": "~1.0.0",
|
||||
"request": "~2.88.0",
|
||||
"socket.io": "~0.9.16",
|
||||
"socket.io-client": "~0.9.16",
|
||||
"sse": "0.0.8"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
standalone-websocket-proxy.js: Example of proxying websockets over HTTP with a standalone HTTP server.
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -24,82 +24,68 @@
|
||||
|
||||
*/
|
||||
|
||||
var sys = require('sys'),
|
||||
var util = require('util'),
|
||||
http = require('http'),
|
||||
colors = require('colors'),
|
||||
websocket = require('../../vendor/websocket'),
|
||||
httpProxy = require('../../lib/node-http-proxy');
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
try {
|
||||
var utils = require('socket.io/lib/socket.io/utils'),
|
||||
io = require('socket.io');
|
||||
var io = require('socket.io'),
|
||||
client = require('socket.io-client');
|
||||
}
|
||||
catch (ex) {
|
||||
console.error('Socket.io is required for this example:');
|
||||
console.error('npm ' + 'install'.green + ' socket.io@0.6.18'.magenta);
|
||||
console.error('npm ' + 'install'.green);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
//
|
||||
// Create the target HTTP server
|
||||
// Create the target HTTP server and setup
|
||||
// socket.io on it.
|
||||
//
|
||||
var server = http.createServer(function (req, res) {
|
||||
res.writeHead(200);
|
||||
res.end();
|
||||
});
|
||||
|
||||
server.listen(8080);
|
||||
|
||||
//
|
||||
// Setup socket.io on the target HTTP server
|
||||
//
|
||||
var socket = io.listen(server);
|
||||
socket.on('connection', function (client) {
|
||||
sys.debug('Got websocket connection');
|
||||
var server = io.listen(9016);
|
||||
server.sockets.on('connection', function (client) {
|
||||
util.debug('Got websocket connection');
|
||||
|
||||
client.on('message', function (msg) {
|
||||
sys.debug('Got message from client: ' + msg);
|
||||
util.debug('Got message from client: ' + msg);
|
||||
});
|
||||
|
||||
socket.broadcast('from server');
|
||||
client.send('from server');
|
||||
});
|
||||
|
||||
//
|
||||
// Setup our server to proxy standard HTTP requests
|
||||
//
|
||||
var proxy = new httpProxy.HttpProxy({
|
||||
var proxy = new httpProxy.createProxyServer({
|
||||
target: {
|
||||
host: 'localhost',
|
||||
port: 8080
|
||||
host: 'localhost',
|
||||
port: 9016
|
||||
}
|
||||
});
|
||||
|
||||
var proxyServer = http.createServer(function (req, res) {
|
||||
proxy.proxyRequest(req, res);
|
||||
proxy.web(req, res);
|
||||
});
|
||||
|
||||
//
|
||||
// Listen to the `upgrade` event and proxy the
|
||||
// Listen to the `upgrade` event and proxy the
|
||||
// WebSocket requests as well.
|
||||
//
|
||||
proxyServer.on('upgrade', function (req, socket, head) {
|
||||
var buffer = httpProxy.buffer(socket);
|
||||
|
||||
setTimeout(function () {
|
||||
proxy.proxyWebSocketRequest(req, socket, head, buffer);
|
||||
proxy.ws(req, socket, head);
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
proxyServer.listen(8081);
|
||||
proxyServer.listen(8016);
|
||||
|
||||
//
|
||||
// Setup the web socket against our proxy
|
||||
// Setup the socket.io client against our proxy
|
||||
//
|
||||
var ws = new websocket.WebSocket('ws://localhost:8081/socket.io/websocket/', 'borf');
|
||||
|
||||
ws.on('open', function () {
|
||||
ws.send(utils.encode('from client'));
|
||||
});
|
||||
var ws = client.connect('ws://localhost:8016');
|
||||
|
||||
ws.on('message', function (msg) {
|
||||
sys.debug('Got message: ' + utils.decode(msg));
|
||||
util.debug('Got message: ' + msg);
|
||||
ws.send('I am the client');
|
||||
});
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
standalone-websocket-proxy.js: Example of proxying websockets over HTTP with a standalone HTTP server.
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -24,78 +24,65 @@
|
||||
|
||||
*/
|
||||
|
||||
var sys = require('sys'),
|
||||
var util = require('util'),
|
||||
http = require('http'),
|
||||
colors = require('colors'),
|
||||
websocket = require('../../vendor/websocket'),
|
||||
httpProxy = require('../../lib/node-http-proxy');
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
try {
|
||||
var utils = require('socket.io/lib/socket.io/utils'),
|
||||
io = require('socket.io');
|
||||
var io = require('socket.io'),
|
||||
client = require('socket.io-client');
|
||||
}
|
||||
catch (ex) {
|
||||
console.error('Socket.io is required for this example:');
|
||||
console.error('npm ' + 'install'.green + ' socket.io@0.6.18'.magenta);
|
||||
console.error('npm ' + 'install'.green);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
//
|
||||
// Create the target HTTP server
|
||||
// Create the target HTTP server and setup
|
||||
// socket.io on it.
|
||||
//
|
||||
var server = http.createServer(function (req, res) {
|
||||
res.writeHead(200);
|
||||
res.end();
|
||||
});
|
||||
|
||||
server.listen(8080);
|
||||
|
||||
//
|
||||
// Setup socket.io on the target HTTP server
|
||||
//
|
||||
var socket = io.listen(server);
|
||||
socket.on('connection', function (client) {
|
||||
sys.debug('Got websocket connection');
|
||||
var server = io.listen(9015);
|
||||
server.sockets.on('connection', function (client) {
|
||||
util.debug('Got websocket connection');
|
||||
|
||||
client.on('message', function (msg) {
|
||||
sys.debug('Got message from client: ' + msg);
|
||||
util.debug('Got message from client: ' + msg);
|
||||
});
|
||||
|
||||
socket.broadcast('from server');
|
||||
client.send('from server');
|
||||
});
|
||||
|
||||
//
|
||||
// Setup our server to proxy standard HTTP requests
|
||||
//
|
||||
var proxy = new httpProxy.HttpProxy({
|
||||
var proxy = new httpProxy.createProxyServer({
|
||||
target: {
|
||||
host: 'localhost',
|
||||
port: 8080
|
||||
host: 'localhost',
|
||||
port: 9015
|
||||
}
|
||||
});
|
||||
var proxyServer = http.createServer(function (req, res) {
|
||||
proxy.proxyRequest(req, res);
|
||||
proxy.web(req, res);
|
||||
});
|
||||
|
||||
//
|
||||
// Listen to the `upgrade` event and proxy the
|
||||
// Listen to the `upgrade` event and proxy the
|
||||
// WebSocket requests as well.
|
||||
//
|
||||
proxyServer.on('upgrade', function (req, socket, head) {
|
||||
proxy.proxyWebSocketRequest(req, socket, head);
|
||||
proxy.ws(req, socket, head);
|
||||
});
|
||||
|
||||
proxyServer.listen(8081);
|
||||
proxyServer.listen(8015);
|
||||
|
||||
//
|
||||
// Setup the web socket against our proxy
|
||||
// Setup the socket.io client against our proxy
|
||||
//
|
||||
var ws = new websocket.WebSocket('ws://localhost:8081/socket.io/websocket/', 'borf');
|
||||
|
||||
ws.on('open', function () {
|
||||
ws.send(utils.encode('from client'));
|
||||
});
|
||||
var ws = client.connect('ws://localhost:8015');
|
||||
|
||||
ws.on('message', function (msg) {
|
||||
sys.debug('Got message: ' + utils.decode(msg));
|
||||
util.debug('Got message: ' + msg);
|
||||
ws.send('I am the client');
|
||||
});
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
/*
|
||||
web-socket-proxy.js: Example of proxying over HTTP and WebSockets.
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
@ -24,61 +24,47 @@
|
||||
|
||||
*/
|
||||
|
||||
var sys = require('sys'),
|
||||
var util = require('util'),
|
||||
http = require('http'),
|
||||
colors = require('colors'),
|
||||
websocket = require('../../vendor/websocket'),
|
||||
httpProxy = require('../../lib/node-http-proxy');
|
||||
httpProxy = require('../../lib/http-proxy');
|
||||
|
||||
try {
|
||||
var utils = require('socket.io/lib/socket.io/utils'),
|
||||
io = require('socket.io');
|
||||
var io = require('socket.io'),
|
||||
client = require('socket.io-client');
|
||||
}
|
||||
catch (ex) {
|
||||
console.error('Socket.io is required for this example:');
|
||||
console.error('npm ' + 'install'.green + ' socket.io@0.6.18'.magenta);
|
||||
console.error('npm ' + 'install'.green);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
//
|
||||
// Create the target HTTP server
|
||||
// Create the target HTTP server and setup
|
||||
// socket.io on it.
|
||||
//
|
||||
var server = http.createServer(function (req, res) {
|
||||
res.writeHead(200);
|
||||
res.end();
|
||||
});
|
||||
|
||||
server.listen(8080);
|
||||
|
||||
//
|
||||
// Setup socket.io on the target HTTP server
|
||||
//
|
||||
var socket = io.listen(server);
|
||||
socket.on('connection', function (client) {
|
||||
sys.debug('Got websocket connection');
|
||||
var server = io.listen(9014);
|
||||
server.sockets.on('connection', function (client) {
|
||||
util.debug('Got websocket connection');
|
||||
|
||||
client.on('message', function (msg) {
|
||||
sys.debug('Got message from client: ' + msg);
|
||||
util.debug('Got message from client: ' + msg);
|
||||
});
|
||||
|
||||
socket.broadcast('from server');
|
||||
client.send('from server');
|
||||
});
|
||||
|
||||
//
|
||||
// Create a proxy server with node-http-proxy
|
||||
//
|
||||
var proxy = httpProxy.createServer(8080, 'localhost');
|
||||
proxy.listen(8081);
|
||||
httpProxy.createServer({ target: 'ws://localhost:9014', ws: true }).listen(8014);
|
||||
|
||||
//
|
||||
// Setup the web socket against our proxy
|
||||
// Setup the socket.io client against our proxy
|
||||
//
|
||||
var ws = new websocket.WebSocket('ws://localhost:8081/socket.io/websocket/', 'borf');
|
||||
|
||||
ws.on('open', function () {
|
||||
ws.send(utils.encode('from client'));
|
||||
});
|
||||
var ws = client.connect('ws://localhost:8014');
|
||||
|
||||
ws.on('message', function (msg) {
|
||||
sys.debug('Got message: ' + utils.decode(msg));
|
||||
util.debug('Got message: ' + msg);
|
||||
ws.send('I am the client');
|
||||
});
|
||||
|
||||
13
index.js
Normal file
13
index.js
Normal file
@ -0,0 +1,13 @@
|
||||
/*!
|
||||
* Caron dimonio, con occhi di bragia
|
||||
* loro accennando, tutte le raccoglie;
|
||||
* batte col remo qualunque s’adagia
|
||||
*
|
||||
* Charon the demon, with the eyes of glede,
|
||||
* Beckoning to them, collects them all together,
|
||||
* Beats with his oar whoever lags behind
|
||||
*
|
||||
* Dante - The Divine Comedy (Canto III)
|
||||
*/
|
||||
|
||||
module.exports = require('./lib/http-proxy');
|
||||
66
lib/http-proxy.js
Normal file
66
lib/http-proxy.js
Normal file
@ -0,0 +1,66 @@
|
||||
// Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!)
|
||||
var ProxyServer = require('./http-proxy/index.js').Server;
|
||||
|
||||
|
||||
/**
|
||||
* Creates the proxy server.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* httpProxy.createProxyServer({ .. }, 8000)
|
||||
* // => '{ web: [Function], ws: [Function] ... }'
|
||||
*
|
||||
* @param {Object} Options Config object passed to the proxy
|
||||
*
|
||||
* @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
|
||||
function createProxyServer(options) {
|
||||
/*
|
||||
* `options` is needed and it must have the following layout:
|
||||
*
|
||||
* {
|
||||
* target : <url string to be parsed with the url module>
|
||||
* forward: <url string to be parsed with the url module>
|
||||
* agent : <object to be passed to http(s).request>
|
||||
* ssl : <object to be passed to https.createServer()>
|
||||
* ws : <true/false, if you want to proxy websockets>
|
||||
* xfwd : <true/false, adds x-forward headers>
|
||||
* secure : <true/false, verify SSL certificate>
|
||||
* toProxy: <true/false, explicitly specify if we are proxying to another proxy>
|
||||
* prependPath: <true/false, Default: true - specify whether you want to prepend the target's path to the proxy path>
|
||||
* ignorePath: <true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request>
|
||||
* localAddress : <Local interface string to bind for outgoing connections>
|
||||
* changeOrigin: <true/false, Default: false - changes the origin of the host header to the target URL>
|
||||
* preserveHeaderKeyCase: <true/false, Default: false - specify whether you want to keep letter case of response header key >
|
||||
* auth : Basic authentication i.e. 'user:password' to compute an Authorization header.
|
||||
* hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null.
|
||||
* autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
|
||||
* protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
|
||||
* }
|
||||
*
|
||||
* NOTE: `options.ws` and `options.ssl` are optional.
|
||||
* `options.target and `options.forward` cannot be
|
||||
* both missing
|
||||
* }
|
||||
*/
|
||||
|
||||
return new ProxyServer(options);
|
||||
}
|
||||
|
||||
|
||||
ProxyServer.createProxyServer = createProxyServer;
|
||||
ProxyServer.createServer = createProxyServer;
|
||||
ProxyServer.createProxy = createProxyServer;
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Export the proxy "Server" as the main export.
|
||||
*/
|
||||
module.exports = ProxyServer;
|
||||
|
||||
248
lib/http-proxy/common.js
Normal file
248
lib/http-proxy/common.js
Normal file
@ -0,0 +1,248 @@
|
||||
var common = exports,
|
||||
url = require('url'),
|
||||
extend = require('util')._extend,
|
||||
required = require('requires-port');
|
||||
|
||||
var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i,
|
||||
isSSL = /^https|wss/;
|
||||
|
||||
/**
|
||||
* Simple Regex for testing if protocol is https
|
||||
*/
|
||||
common.isSSL = isSSL;
|
||||
/**
|
||||
* Copies the right headers from `options` and `req` to
|
||||
* `outgoing` which is then used to fire the proxied
|
||||
* request.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* common.setupOutgoing(outgoing, options, req)
|
||||
* // => { host: ..., hostname: ...}
|
||||
*
|
||||
* @param {Object} Outgoing Base object to be filled with required properties
|
||||
* @param {Object} Options Config object passed to the proxy
|
||||
* @param {ClientRequest} Req Request Object
|
||||
* @param {String} Forward String to select forward or target
|
||||
*
|
||||
* @return {Object} Outgoing Object with all required properties set
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
common.setupOutgoing = function(outgoing, options, req, forward) {
|
||||
outgoing.port = options[forward || 'target'].port ||
|
||||
(isSSL.test(options[forward || 'target'].protocol) ? 443 : 80);
|
||||
|
||||
['host', 'hostname', 'socketPath', 'pfx', 'key',
|
||||
'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach(
|
||||
function(e) { outgoing[e] = options[forward || 'target'][e]; }
|
||||
);
|
||||
|
||||
outgoing.method = options.method || req.method;
|
||||
outgoing.headers = extend({}, req.headers);
|
||||
|
||||
if (options.headers){
|
||||
extend(outgoing.headers, options.headers);
|
||||
}
|
||||
|
||||
if (options.auth) {
|
||||
outgoing.auth = options.auth;
|
||||
}
|
||||
|
||||
if (options.ca) {
|
||||
outgoing.ca = options.ca;
|
||||
}
|
||||
|
||||
if (isSSL.test(options[forward || 'target'].protocol)) {
|
||||
outgoing.rejectUnauthorized = (typeof options.secure === "undefined") ? true : options.secure;
|
||||
}
|
||||
|
||||
|
||||
outgoing.agent = options.agent || false;
|
||||
outgoing.localAddress = options.localAddress;
|
||||
|
||||
//
|
||||
// Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do
|
||||
// as node core doesn't handle this COMPLETELY properly yet.
|
||||
//
|
||||
if (!outgoing.agent) {
|
||||
outgoing.headers = outgoing.headers || {};
|
||||
if (typeof outgoing.headers.connection !== 'string'
|
||||
|| !upgradeHeader.test(outgoing.headers.connection)
|
||||
) { outgoing.headers.connection = 'close'; }
|
||||
}
|
||||
|
||||
|
||||
// the final path is target path + relative path requested by user:
|
||||
var target = options[forward || 'target'];
|
||||
var targetPath = target && options.prependPath !== false
|
||||
? (target.path || '')
|
||||
: '';
|
||||
|
||||
//
|
||||
// Remark: Can we somehow not use url.parse as a perf optimization?
|
||||
//
|
||||
var outgoingPath = !options.toProxy
|
||||
? (url.parse(req.url).path || '')
|
||||
: req.url;
|
||||
|
||||
//
|
||||
// Remark: ignorePath will just straight up ignore whatever the request's
|
||||
// path is. This can be labeled as FOOT-GUN material if you do not know what
|
||||
// you are doing and are using conflicting options.
|
||||
//
|
||||
outgoingPath = !options.ignorePath ? outgoingPath : '';
|
||||
|
||||
outgoing.path = common.urlJoin(targetPath, outgoingPath);
|
||||
|
||||
if (options.changeOrigin) {
|
||||
outgoing.headers.host =
|
||||
required(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host)
|
||||
? outgoing.host + ':' + outgoing.port
|
||||
: outgoing.host;
|
||||
}
|
||||
return outgoing;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the proper configuration for sockets,
|
||||
* set no delay and set keep alive, also set
|
||||
* the timeout to 0.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* common.setupSocket(socket)
|
||||
* // => Socket
|
||||
*
|
||||
* @param {Socket} Socket instance to setup
|
||||
*
|
||||
* @return {Socket} Return the configured socket.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
common.setupSocket = function(socket) {
|
||||
socket.setTimeout(0);
|
||||
socket.setNoDelay(true);
|
||||
|
||||
socket.setKeepAlive(true, 0);
|
||||
|
||||
return socket;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the port number from the host. Or guess it based on the connection type.
|
||||
*
|
||||
* @param {Request} req Incoming HTTP request.
|
||||
*
|
||||
* @return {String} The port number.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
common.getPort = function(req) {
|
||||
var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : '';
|
||||
|
||||
return res ?
|
||||
res[1] :
|
||||
common.hasEncryptedConnection(req) ? '443' : '80';
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if the request has an encrypted connection.
|
||||
*
|
||||
* @param {Request} req Incoming HTTP request.
|
||||
*
|
||||
* @return {Boolean} Whether the connection is encrypted or not.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
common.hasEncryptedConnection = function(req) {
|
||||
return Boolean(req.connection.encrypted || req.connection.pair);
|
||||
};
|
||||
|
||||
/**
|
||||
* OS-agnostic join (doesn't break on URLs like path.join does on Windows)>
|
||||
*
|
||||
* @return {String} The generated path.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
common.urlJoin = function() {
|
||||
//
|
||||
// We do not want to mess with the query string. All we want to touch is the path.
|
||||
//
|
||||
var args = Array.prototype.slice.call(arguments),
|
||||
lastIndex = args.length - 1,
|
||||
last = args[lastIndex],
|
||||
lastSegs = last.split('?'),
|
||||
retSegs;
|
||||
|
||||
args[lastIndex] = lastSegs.shift();
|
||||
|
||||
//
|
||||
// Join all strings, but remove empty strings so we don't get extra slashes from
|
||||
// joining e.g. ['', 'am']
|
||||
//
|
||||
retSegs = [
|
||||
args.filter(Boolean).join('/')
|
||||
.replace(/\/+/g, '/')
|
||||
.replace('http:/', 'http://')
|
||||
.replace('https:/', 'https://')
|
||||
];
|
||||
|
||||
// Only join the query string if it exists so we don't have trailing a '?'
|
||||
// on every request
|
||||
|
||||
// Handle case where there could be multiple ? in the URL.
|
||||
retSegs.push.apply(retSegs, lastSegs);
|
||||
|
||||
return retSegs.join('?')
|
||||
};
|
||||
|
||||
/**
|
||||
* Rewrites or removes the domain of a cookie header
|
||||
*
|
||||
* @param {String|Array} Header
|
||||
* @param {Object} Config, mapping of domain to rewritten domain.
|
||||
* '*' key to match any domain, null value to remove the domain.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) {
|
||||
if (Array.isArray(header)) {
|
||||
return header.map(function (headerElement) {
|
||||
return rewriteCookieProperty(headerElement, config, property);
|
||||
});
|
||||
}
|
||||
return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) {
|
||||
var newValue;
|
||||
if (previousValue in config) {
|
||||
newValue = config[previousValue];
|
||||
} else if ('*' in config) {
|
||||
newValue = config['*'];
|
||||
} else {
|
||||
//no match, return previous value
|
||||
return match;
|
||||
}
|
||||
if (newValue) {
|
||||
//replace value
|
||||
return prefix + newValue;
|
||||
} else {
|
||||
//remove value
|
||||
return '';
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Check the host and see if it potentially has a port in it (keep it simple)
|
||||
*
|
||||
* @returns {Boolean} Whether we have one or not
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
function hasPort(host) {
|
||||
return !!~host.indexOf(':');
|
||||
};
|
||||
185
lib/http-proxy/index.js
Normal file
185
lib/http-proxy/index.js
Normal file
@ -0,0 +1,185 @@
|
||||
var httpProxy = module.exports,
|
||||
extend = require('util')._extend,
|
||||
parse_url = require('url').parse,
|
||||
EE3 = require('eventemitter3'),
|
||||
http = require('http'),
|
||||
https = require('https'),
|
||||
web = require('./passes/web-incoming'),
|
||||
ws = require('./passes/ws-incoming');
|
||||
|
||||
httpProxy.Server = ProxyServer;
|
||||
|
||||
/**
|
||||
* Returns a function that creates the loader for
|
||||
* either `ws` or `web`'s passes.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* httpProxy.createRightProxy('ws')
|
||||
* // => [Function]
|
||||
*
|
||||
* @param {String} Type Either 'ws' or 'web'
|
||||
*
|
||||
* @return {Function} Loader Function that when called returns an iterator for the right passes
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function createRightProxy(type) {
|
||||
|
||||
return function(options) {
|
||||
return function(req, res /*, [head], [opts] */) {
|
||||
var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
|
||||
args = [].slice.call(arguments),
|
||||
cntr = args.length - 1,
|
||||
head, cbl;
|
||||
|
||||
/* optional args parse begin */
|
||||
if(typeof args[cntr] === 'function') {
|
||||
cbl = args[cntr];
|
||||
|
||||
cntr--;
|
||||
}
|
||||
|
||||
var requestOptions = options;
|
||||
if(
|
||||
!(args[cntr] instanceof Buffer) &&
|
||||
args[cntr] !== res
|
||||
) {
|
||||
//Copy global options
|
||||
requestOptions = extend({}, options);
|
||||
//Overwrite with request options
|
||||
extend(requestOptions, args[cntr]);
|
||||
|
||||
cntr--;
|
||||
}
|
||||
|
||||
if(args[cntr] instanceof Buffer) {
|
||||
head = args[cntr];
|
||||
}
|
||||
|
||||
/* optional args parse end */
|
||||
|
||||
['target', 'forward'].forEach(function(e) {
|
||||
if (typeof requestOptions[e] === 'string')
|
||||
requestOptions[e] = parse_url(requestOptions[e]);
|
||||
});
|
||||
|
||||
if (!requestOptions.target && !requestOptions.forward) {
|
||||
return this.emit('error', new Error('Must provide a proper URL as target'));
|
||||
}
|
||||
|
||||
for(var i=0; i < passes.length; i++) {
|
||||
/**
|
||||
* Call of passes functions
|
||||
* pass(req, res, options, head)
|
||||
*
|
||||
* In WebSockets case the `res` variable
|
||||
* refer to the connection socket
|
||||
* pass(req, socket, options, head)
|
||||
*/
|
||||
if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
httpProxy.createRightProxy = createRightProxy;
|
||||
|
||||
function ProxyServer(options) {
|
||||
EE3.call(this);
|
||||
|
||||
options = options || {};
|
||||
options.prependPath = options.prependPath === false ? false : true;
|
||||
|
||||
this.web = this.proxyRequest = createRightProxy('web')(options);
|
||||
this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options);
|
||||
this.options = options;
|
||||
|
||||
this.webPasses = Object.keys(web).map(function(pass) {
|
||||
return web[pass];
|
||||
});
|
||||
|
||||
this.wsPasses = Object.keys(ws).map(function(pass) {
|
||||
return ws[pass];
|
||||
});
|
||||
|
||||
this.on('error', this.onError, this);
|
||||
|
||||
}
|
||||
|
||||
require('util').inherits(ProxyServer, EE3);
|
||||
|
||||
ProxyServer.prototype.onError = function (err) {
|
||||
//
|
||||
// Remark: Replicate node core behavior using EE3
|
||||
// so we force people to handle their own errors
|
||||
//
|
||||
if(this.listeners('error').length === 1) {
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
ProxyServer.prototype.listen = function(port, hostname) {
|
||||
var self = this,
|
||||
closure = function(req, res) { self.web(req, res); };
|
||||
|
||||
this._server = this.options.ssl ?
|
||||
https.createServer(this.options.ssl, closure) :
|
||||
http.createServer(closure);
|
||||
|
||||
if(this.options.ws) {
|
||||
this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); });
|
||||
}
|
||||
|
||||
this._server.listen(port, hostname);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
ProxyServer.prototype.close = function(callback) {
|
||||
var self = this;
|
||||
if (this._server) {
|
||||
this._server.close(done);
|
||||
}
|
||||
|
||||
// Wrap callback to nullify server after all open connections are closed.
|
||||
function done() {
|
||||
self._server = null;
|
||||
if (callback) {
|
||||
callback.apply(null, arguments);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
ProxyServer.prototype.before = function(type, passName, callback) {
|
||||
if (type !== 'ws' && type !== 'web') {
|
||||
throw new Error('type must be `web` or `ws`');
|
||||
}
|
||||
var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
|
||||
i = false;
|
||||
|
||||
passes.forEach(function(v, idx) {
|
||||
if(v.name === passName) i = idx;
|
||||
})
|
||||
|
||||
if(i === false) throw new Error('No such pass');
|
||||
|
||||
passes.splice(i, 0, callback);
|
||||
};
|
||||
ProxyServer.prototype.after = function(type, passName, callback) {
|
||||
if (type !== 'ws' && type !== 'web') {
|
||||
throw new Error('type must be `web` or `ws`');
|
||||
}
|
||||
var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
|
||||
i = false;
|
||||
|
||||
passes.forEach(function(v, idx) {
|
||||
if(v.name === passName) i = idx;
|
||||
})
|
||||
|
||||
if(i === false) throw new Error('No such pass');
|
||||
|
||||
passes.splice(i++, 0, callback);
|
||||
};
|
||||
194
lib/http-proxy/passes/web-incoming.js
Normal file
194
lib/http-proxy/passes/web-incoming.js
Normal file
@ -0,0 +1,194 @@
|
||||
var httpNative = require('http'),
|
||||
httpsNative = require('https'),
|
||||
web_o = require('./web-outgoing'),
|
||||
common = require('../common'),
|
||||
followRedirects = require('follow-redirects');
|
||||
|
||||
web_o = Object.keys(web_o).map(function(pass) {
|
||||
return web_o[pass];
|
||||
});
|
||||
|
||||
var nativeAgents = { http: httpNative, https: httpsNative };
|
||||
|
||||
/*!
|
||||
* Array of passes.
|
||||
*
|
||||
* A `pass` is just a function that is executed on `req, res, options`
|
||||
* so that you can easily add new checks while still keeping the base
|
||||
* flexible.
|
||||
*/
|
||||
|
||||
|
||||
module.exports = {
|
||||
|
||||
/**
|
||||
* Sets `content-length` to '0' if request is of DELETE type.
|
||||
*
|
||||
* @param {ClientRequest} Req Request object
|
||||
* @param {IncomingMessage} Res Response object
|
||||
* @param {Object} Options Config object passed to the proxy
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
deleteLength: function deleteLength(req, res, options) {
|
||||
if((req.method === 'DELETE' || req.method === 'OPTIONS')
|
||||
&& !req.headers['content-length']) {
|
||||
req.headers['content-length'] = '0';
|
||||
delete req.headers['transfer-encoding'];
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets timeout in request socket if it was specified in options.
|
||||
*
|
||||
* @param {ClientRequest} Req Request object
|
||||
* @param {IncomingMessage} Res Response object
|
||||
* @param {Object} Options Config object passed to the proxy
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
timeout: function timeout(req, res, options) {
|
||||
if(options.timeout) {
|
||||
req.socket.setTimeout(options.timeout);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets `x-forwarded-*` headers if specified in config.
|
||||
*
|
||||
* @param {ClientRequest} Req Request object
|
||||
* @param {IncomingMessage} Res Response object
|
||||
* @param {Object} Options Config object passed to the proxy
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
XHeaders: function XHeaders(req, res, options) {
|
||||
if(!options.xfwd) return;
|
||||
|
||||
var encrypted = req.isSpdy || common.hasEncryptedConnection(req);
|
||||
var values = {
|
||||
for : req.connection.remoteAddress || req.socket.remoteAddress,
|
||||
port : common.getPort(req),
|
||||
proto: encrypted ? 'https' : 'http'
|
||||
};
|
||||
|
||||
['for', 'port', 'proto'].forEach(function(header) {
|
||||
req.headers['x-forwarded-' + header] =
|
||||
(req.headers['x-forwarded-' + header] || '') +
|
||||
(req.headers['x-forwarded-' + header] ? ',' : '') +
|
||||
values[header];
|
||||
});
|
||||
|
||||
req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || '';
|
||||
},
|
||||
|
||||
/**
|
||||
* Does the actual proxying. If `forward` is enabled fires up
|
||||
* a ForwardStream, same happens for ProxyStream. The request
|
||||
* just dies otherwise.
|
||||
*
|
||||
* @param {ClientRequest} Req Request object
|
||||
* @param {IncomingMessage} Res Response object
|
||||
* @param {Object} Options Config object passed to the proxy
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
stream: function stream(req, res, options, _, server, clb) {
|
||||
|
||||
// And we begin!
|
||||
server.emit('start', req, res, options.target || options.forward);
|
||||
|
||||
var agents = options.followRedirects ? followRedirects : nativeAgents;
|
||||
var http = agents.http;
|
||||
var https = agents.https;
|
||||
|
||||
if(options.forward) {
|
||||
// If forward enable, so just pipe the request
|
||||
var forwardReq = (options.forward.protocol === 'https:' ? https : http).request(
|
||||
common.setupOutgoing(options.ssl || {}, options, req, 'forward')
|
||||
);
|
||||
|
||||
// error handler (e.g. ECONNRESET, ECONNREFUSED)
|
||||
// Handle errors on incoming request as well as it makes sense to
|
||||
var forwardError = createErrorHandler(forwardReq, options.forward);
|
||||
req.on('error', forwardError);
|
||||
forwardReq.on('error', forwardError);
|
||||
|
||||
(options.buffer || req).pipe(forwardReq);
|
||||
if(!options.target) { return res.end(); }
|
||||
}
|
||||
|
||||
// Request initalization
|
||||
var proxyReq = (options.target.protocol === 'https:' ? https : http).request(
|
||||
common.setupOutgoing(options.ssl || {}, options, req)
|
||||
);
|
||||
|
||||
// Enable developers to modify the proxyReq before headers are sent
|
||||
proxyReq.on('socket', function(socket) {
|
||||
if(server && !proxyReq.getHeader('expect')) {
|
||||
server.emit('proxyReq', proxyReq, req, res, options);
|
||||
}
|
||||
});
|
||||
|
||||
// allow outgoing socket to timeout so that we could
|
||||
// show an error page at the initial request
|
||||
if(options.proxyTimeout) {
|
||||
proxyReq.setTimeout(options.proxyTimeout, function() {
|
||||
proxyReq.abort();
|
||||
});
|
||||
}
|
||||
|
||||
// Ensure we abort proxy if request is aborted
|
||||
req.on('aborted', function () {
|
||||
proxyReq.abort();
|
||||
});
|
||||
|
||||
// handle errors in proxy and incoming request, just like for forward proxy
|
||||
var proxyError = createErrorHandler(proxyReq, options.target);
|
||||
req.on('error', proxyError);
|
||||
proxyReq.on('error', proxyError);
|
||||
|
||||
function createErrorHandler(proxyReq, url) {
|
||||
return function proxyError(err) {
|
||||
if (req.socket.destroyed && err.code === 'ECONNRESET') {
|
||||
server.emit('econnreset', err, req, res, url);
|
||||
return proxyReq.abort();
|
||||
}
|
||||
|
||||
if (clb) {
|
||||
clb(err, req, res, url);
|
||||
} else {
|
||||
server.emit('error', err, req, res, url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(options.buffer || req).pipe(proxyReq);
|
||||
|
||||
proxyReq.on('response', function(proxyRes) {
|
||||
if(server) { server.emit('proxyRes', proxyRes, req, res); }
|
||||
|
||||
if(!res.headersSent && !options.selfHandleResponse) {
|
||||
for(var i=0; i < web_o.length; i++) {
|
||||
if(web_o[i](req, res, proxyRes, options)) { break; }
|
||||
}
|
||||
}
|
||||
|
||||
if (!res.finished) {
|
||||
// Allow us to listen when the proxy has completed
|
||||
proxyRes.on('end', function () {
|
||||
if (server) server.emit('end', req, res, proxyRes);
|
||||
});
|
||||
// We pipe to the response unless its expected to be handled by the user
|
||||
if (!options.selfHandleResponse) proxyRes.pipe(res);
|
||||
} else {
|
||||
if (server) server.emit('end', req, res, proxyRes);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
};
|
||||
147
lib/http-proxy/passes/web-outgoing.js
Normal file
147
lib/http-proxy/passes/web-outgoing.js
Normal file
@ -0,0 +1,147 @@
|
||||
var url = require('url'),
|
||||
common = require('../common');
|
||||
|
||||
|
||||
var redirectRegex = /^201|30(1|2|7|8)$/;
|
||||
|
||||
/*!
|
||||
* Array of passes.
|
||||
*
|
||||
* A `pass` is just a function that is executed on `req, res, options`
|
||||
* so that you can easily add new checks while still keeping the base
|
||||
* flexible.
|
||||
*/
|
||||
|
||||
module.exports = { // <--
|
||||
|
||||
/**
|
||||
* If is a HTTP 1.0 request, remove chunk headers
|
||||
*
|
||||
* @param {ClientRequest} Req Request object
|
||||
* @param {IncomingMessage} Res Response object
|
||||
* @param {proxyResponse} Res Response object from the proxy request
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
removeChunked: function removeChunked(req, res, proxyRes) {
|
||||
if (req.httpVersion === '1.0') {
|
||||
delete proxyRes.headers['transfer-encoding'];
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* If is a HTTP 1.0 request, set the correct connection header
|
||||
* or if connection header not present, then use `keep-alive`
|
||||
*
|
||||
* @param {ClientRequest} Req Request object
|
||||
* @param {IncomingMessage} Res Response object
|
||||
* @param {proxyResponse} Res Response object from the proxy request
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
setConnection: function setConnection(req, res, proxyRes) {
|
||||
if (req.httpVersion === '1.0') {
|
||||
proxyRes.headers.connection = req.headers.connection || 'close';
|
||||
} else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) {
|
||||
proxyRes.headers.connection = req.headers.connection || 'keep-alive';
|
||||
}
|
||||
},
|
||||
|
||||
setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) {
|
||||
if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite)
|
||||
&& proxyRes.headers['location']
|
||||
&& redirectRegex.test(proxyRes.statusCode)) {
|
||||
var target = url.parse(options.target);
|
||||
var u = url.parse(proxyRes.headers['location']);
|
||||
|
||||
// make sure the redirected host matches the target host before rewriting
|
||||
if (target.host != u.host) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.hostRewrite) {
|
||||
u.host = options.hostRewrite;
|
||||
} else if (options.autoRewrite) {
|
||||
u.host = req.headers['host'];
|
||||
}
|
||||
if (options.protocolRewrite) {
|
||||
u.protocol = options.protocolRewrite;
|
||||
}
|
||||
|
||||
proxyRes.headers['location'] = u.format();
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Copy headers from proxyResponse to response
|
||||
* set each header in response object.
|
||||
*
|
||||
* @param {ClientRequest} Req Request object
|
||||
* @param {IncomingMessage} Res Response object
|
||||
* @param {proxyResponse} Res Response object from the proxy request
|
||||
* @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
writeHeaders: function writeHeaders(req, res, proxyRes, options) {
|
||||
var rewriteCookieDomainConfig = options.cookieDomainRewrite,
|
||||
rewriteCookiePathConfig = options.cookiePathRewrite,
|
||||
preserveHeaderKeyCase = options.preserveHeaderKeyCase,
|
||||
rawHeaderKeyMap,
|
||||
setHeader = function(key, header) {
|
||||
if (header == undefined) return;
|
||||
if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') {
|
||||
header = common.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain');
|
||||
}
|
||||
if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') {
|
||||
header = common.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path');
|
||||
}
|
||||
res.setHeader(String(key).trim(), header);
|
||||
};
|
||||
|
||||
if (typeof rewriteCookieDomainConfig === 'string') { //also test for ''
|
||||
rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig };
|
||||
}
|
||||
|
||||
if (typeof rewriteCookiePathConfig === 'string') { //also test for ''
|
||||
rewriteCookiePathConfig = { '*': rewriteCookiePathConfig };
|
||||
}
|
||||
|
||||
// message.rawHeaders is added in: v0.11.6
|
||||
// https://nodejs.org/api/http.html#http_message_rawheaders
|
||||
if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) {
|
||||
rawHeaderKeyMap = {};
|
||||
for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) {
|
||||
var key = proxyRes.rawHeaders[i];
|
||||
rawHeaderKeyMap[key.toLowerCase()] = key;
|
||||
}
|
||||
}
|
||||
|
||||
Object.keys(proxyRes.headers).forEach(function(key) {
|
||||
var header = proxyRes.headers[key];
|
||||
if (preserveHeaderKeyCase && rawHeaderKeyMap) {
|
||||
key = rawHeaderKeyMap[key] || key;
|
||||
}
|
||||
setHeader(key, header);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the statusCode from the proxyResponse
|
||||
*
|
||||
* @param {ClientRequest} Req Request object
|
||||
* @param {IncomingMessage} Res Response object
|
||||
* @param {proxyResponse} Res Response object from the proxy request
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
writeStatusCode: function writeStatusCode(req, res, proxyRes) {
|
||||
// From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers])
|
||||
if(proxyRes.statusMessage) {
|
||||
res.statusCode = proxyRes.statusCode;
|
||||
res.statusMessage = proxyRes.statusMessage;
|
||||
} else {
|
||||
res.statusCode = proxyRes.statusCode;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
162
lib/http-proxy/passes/ws-incoming.js
Normal file
162
lib/http-proxy/passes/ws-incoming.js
Normal file
@ -0,0 +1,162 @@
|
||||
var http = require('http'),
|
||||
https = require('https'),
|
||||
common = require('../common');
|
||||
|
||||
/*!
|
||||
* Array of passes.
|
||||
*
|
||||
* A `pass` is just a function that is executed on `req, socket, options`
|
||||
* so that you can easily add new checks while still keeping the base
|
||||
* flexible.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Websockets Passes
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* WebSocket requests must have the `GET` method and
|
||||
* the `upgrade:websocket` header
|
||||
*
|
||||
* @param {ClientRequest} Req Request object
|
||||
* @param {Socket} Websocket
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
checkMethodAndHeader : function checkMethodAndHeader(req, socket) {
|
||||
if (req.method !== 'GET' || !req.headers.upgrade) {
|
||||
socket.destroy();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (req.headers.upgrade.toLowerCase() !== 'websocket') {
|
||||
socket.destroy();
|
||||
return true;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets `x-forwarded-*` headers if specified in config.
|
||||
*
|
||||
* @param {ClientRequest} Req Request object
|
||||
* @param {Socket} Websocket
|
||||
* @param {Object} Options Config object passed to the proxy
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
XHeaders : function XHeaders(req, socket, options) {
|
||||
if(!options.xfwd) return;
|
||||
|
||||
var values = {
|
||||
for : req.connection.remoteAddress || req.socket.remoteAddress,
|
||||
port : common.getPort(req),
|
||||
proto: common.hasEncryptedConnection(req) ? 'wss' : 'ws'
|
||||
};
|
||||
|
||||
['for', 'port', 'proto'].forEach(function(header) {
|
||||
req.headers['x-forwarded-' + header] =
|
||||
(req.headers['x-forwarded-' + header] || '') +
|
||||
(req.headers['x-forwarded-' + header] ? ',' : '') +
|
||||
values[header];
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Does the actual proxying. Make the request and upgrade it
|
||||
* send the Switching Protocols request and pipe the sockets.
|
||||
*
|
||||
* @param {ClientRequest} Req Request object
|
||||
* @param {Socket} Websocket
|
||||
* @param {Object} Options Config object passed to the proxy
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
stream : function stream(req, socket, options, head, server, clb) {
|
||||
|
||||
var createHttpHeader = function(line, headers) {
|
||||
return Object.keys(headers).reduce(function (head, key) {
|
||||
var value = headers[key];
|
||||
|
||||
if (!Array.isArray(value)) {
|
||||
head.push(key + ': ' + value);
|
||||
return head;
|
||||
}
|
||||
|
||||
for (var i = 0; i < value.length; i++) {
|
||||
head.push(key + ': ' + value[i]);
|
||||
}
|
||||
return head;
|
||||
}, [line])
|
||||
.join('\r\n') + '\r\n\r\n';
|
||||
}
|
||||
|
||||
common.setupSocket(socket);
|
||||
|
||||
if (head && head.length) socket.unshift(head);
|
||||
|
||||
|
||||
var proxyReq = (common.isSSL.test(options.target.protocol) ? https : http).request(
|
||||
common.setupOutgoing(options.ssl || {}, options, req)
|
||||
);
|
||||
|
||||
// Enable developers to modify the proxyReq before headers are sent
|
||||
if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); }
|
||||
|
||||
// Error Handler
|
||||
proxyReq.on('error', onOutgoingError);
|
||||
proxyReq.on('response', function (res) {
|
||||
// if upgrade event isn't going to happen, close the socket
|
||||
if (!res.upgrade) {
|
||||
socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers));
|
||||
res.pipe(socket);
|
||||
}
|
||||
});
|
||||
|
||||
proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
|
||||
proxySocket.on('error', onOutgoingError);
|
||||
|
||||
// Allow us to listen when the websocket has completed
|
||||
proxySocket.on('end', function () {
|
||||
server.emit('close', proxyRes, proxySocket, proxyHead);
|
||||
});
|
||||
|
||||
// The pipe below will end proxySocket if socket closes cleanly, but not
|
||||
// if it errors (eg, vanishes from the net and starts returning
|
||||
// EHOSTUNREACH). We need to do that explicitly.
|
||||
socket.on('error', function () {
|
||||
proxySocket.end();
|
||||
});
|
||||
|
||||
common.setupSocket(proxySocket);
|
||||
|
||||
if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
|
||||
|
||||
//
|
||||
// Remark: Handle writing the headers to the socket when switching protocols
|
||||
// Also handles when a header is an array
|
||||
//
|
||||
socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers));
|
||||
|
||||
proxySocket.pipe(socket).pipe(proxySocket);
|
||||
|
||||
server.emit('open', proxySocket);
|
||||
server.emit('proxySocket', proxySocket); //DEPRECATED.
|
||||
});
|
||||
|
||||
return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT
|
||||
|
||||
function onOutgoingError(err) {
|
||||
if (clb) {
|
||||
clb(err, req, socket);
|
||||
} else {
|
||||
server.emit('error', err, req, socket);
|
||||
}
|
||||
socket.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -1,394 +0,0 @@
|
||||
/*
|
||||
node-http-proxy.js: http proxy for node.js
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Marak Squires, Fedor Indutny
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
var util = require('util'),
|
||||
http = require('http'),
|
||||
https = require('https'),
|
||||
events = require('events'),
|
||||
maxSockets = 100;
|
||||
|
||||
//
|
||||
// Expose version information through `pkginfo`.
|
||||
//
|
||||
require('pkginfo')(module, 'version');
|
||||
|
||||
//
|
||||
// ### Export the relevant objects exposed by `node-http-proxy`
|
||||
//
|
||||
var HttpProxy = exports.HttpProxy = require('./node-http-proxy/http-proxy').HttpProxy,
|
||||
ProxyTable = exports.ProxyTable = require('./node-http-proxy/proxy-table').ProxyTable,
|
||||
RoutingProxy = exports.RoutingProxy = require('./node-http-proxy/routing-proxy').RoutingProxy;
|
||||
|
||||
//
|
||||
// ### function createServer ([port, host, options, handler])
|
||||
// #### @port {number} **Optional** Port to use on the proxy target host.
|
||||
// #### @host {string} **Optional** Host of the proxy target.
|
||||
// #### @options {Object} **Optional** Options for the HttpProxy instance used
|
||||
// #### @handler {function} **Optional** Request handler for the server
|
||||
// Returns a server that manages an instance of HttpProxy. Flexible arguments allow for:
|
||||
//
|
||||
// * `httpProxy.createServer(9000, 'localhost')`
|
||||
// * `httpProxy.createServer(9000, 'localhost', options)
|
||||
// * `httpPRoxy.createServer(function (req, res, proxy) { ... })`
|
||||
//
|
||||
exports.createServer = function () {
|
||||
var args = Array.prototype.slice.call(arguments),
|
||||
handlers = [],
|
||||
options = {},
|
||||
message,
|
||||
handler,
|
||||
server,
|
||||
proxy,
|
||||
host,
|
||||
port;
|
||||
|
||||
//
|
||||
// Liberally parse arguments of the form:
|
||||
//
|
||||
// httpProxy.createServer('localhost', 9000, callback);
|
||||
// httpProxy.createServer({ host: 'localhost', port: 9000 }, callback);
|
||||
// **NEED MORE HERE!!!**
|
||||
//
|
||||
args.forEach(function (arg) {
|
||||
switch (typeof arg) {
|
||||
case 'string': host = arg; break;
|
||||
case 'number': port = arg; break;
|
||||
case 'object': options = arg || {}; break;
|
||||
case 'function': handlers.push(arg); break;
|
||||
};
|
||||
});
|
||||
|
||||
//
|
||||
// Helper function to create intelligent error message(s)
|
||||
// for the very liberal arguments parsing performed by
|
||||
// `require('http-proxy').createServer()`.
|
||||
//
|
||||
function validArguments() {
|
||||
var conditions = {
|
||||
'port and host': function () {
|
||||
return port && host;
|
||||
},
|
||||
'options.target or options.router': function () {
|
||||
return options && (options.router ||
|
||||
(options.target && options.target.host && options.target.port));
|
||||
},
|
||||
'or proxy handlers': function () {
|
||||
return handlers && handlers.length;
|
||||
}
|
||||
}
|
||||
|
||||
var missing = Object.keys(conditions).filter(function (name) {
|
||||
return !conditions[name]();
|
||||
});
|
||||
|
||||
if (missing.length === 3) {
|
||||
message = 'Cannot proxy without ' + missing.join(', ');
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!validArguments()) {
|
||||
//
|
||||
// If `host`, `port` and `options` are all not passed (with valid
|
||||
// options) then this server is improperly configured.
|
||||
//
|
||||
throw new Error(message);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Hoist up any explicit `host` or `port` arguments
|
||||
// that have been passed in to the options we will
|
||||
// pass to the `httpProxy.HttpProxy` constructor.
|
||||
//
|
||||
options.target = options.target || {};
|
||||
options.target.port = options.target.port || port;
|
||||
options.target.host = options.target.host || host;
|
||||
|
||||
if (options.target && options.target.host && options.target.port) {
|
||||
//
|
||||
// If an explicit `host` and `port` combination has been passed
|
||||
// to `.createServer()` then instantiate a hot-path optimized
|
||||
// `HttpProxy` object and add the "proxy" middleware layer.
|
||||
//
|
||||
proxy = new HttpProxy(options);
|
||||
handlers.push(function (req, res) {
|
||||
proxy.proxyRequest(req, res);
|
||||
});
|
||||
}
|
||||
else {
|
||||
//
|
||||
// If no explicit `host` or `port` combination has been passed then
|
||||
// we have to assume that this is a "go-anywhere" Proxy (i.e. a `RoutingProxy`).
|
||||
//
|
||||
proxy = new RoutingProxy(options);
|
||||
|
||||
if (options.router) {
|
||||
//
|
||||
// If a routing table has been supplied than we assume
|
||||
// the user intends us to add the "proxy" middleware layer
|
||||
// for them
|
||||
//
|
||||
handlers.push(function (req, res) {
|
||||
proxy.proxyRequest(req, res);
|
||||
});
|
||||
|
||||
proxy.on('routes', function (routes) {
|
||||
server.emit('routes', routes);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Create the `http[s].Server` instance which will use
|
||||
// an instance of `httpProxy.HttpProxy`.
|
||||
//
|
||||
handler = handlers.length > 1
|
||||
? exports.stack(handlers, proxy)
|
||||
: function (req, res) { handlers[0](req, res, proxy) };
|
||||
|
||||
server = options.https
|
||||
? https.createServer(options.https, handler)
|
||||
: http.createServer(handler);
|
||||
|
||||
server.on('close', function () {
|
||||
proxy.close();
|
||||
});
|
||||
|
||||
if (handlers.length <= 1) {
|
||||
//
|
||||
// If an explicit callback has not been supplied then
|
||||
// automagically proxy the request using the `HttpProxy`
|
||||
// instance we have created.
|
||||
//
|
||||
server.on('upgrade', function (req, socket, head) {
|
||||
proxy.proxyWebSocketRequest(req, socket, head);
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Set the proxy on the server so it is available
|
||||
// to the consumer of the server
|
||||
//
|
||||
server.proxy = proxy;
|
||||
return server;
|
||||
};
|
||||
|
||||
//
|
||||
// ### function buffer (obj)
|
||||
// #### @obj {Object} Object to pause events from
|
||||
// Buffer `data` and `end` events from the given `obj`.
|
||||
// Consumers of HttpProxy performing async tasks
|
||||
// __must__ utilize this utility, to re-emit data once
|
||||
// the async operation has completed, otherwise these
|
||||
// __events will be lost.__
|
||||
//
|
||||
// var buffer = httpProxy.buffer(req);
|
||||
// fs.readFile(path, function(){
|
||||
// httpProxy.proxyRequest(req, res, host, port, buffer);
|
||||
// });
|
||||
//
|
||||
// __Attribution:__ This approach is based heavily on
|
||||
// [Connect](https://github.com/senchalabs/connect/blob/master/lib/utils.js#L157).
|
||||
// However, this is not a big leap from the implementation in node-http-proxy < 0.4.0.
|
||||
// This simply chooses to manage the scope of the events on a new Object literal as opposed to
|
||||
// [on the HttpProxy instance](https://github.com/nodejitsu/node-http-proxy/blob/v0.3.1/lib/node-http-proxy.js#L154).
|
||||
//
|
||||
exports.buffer = function (obj) {
|
||||
var events = [],
|
||||
onData,
|
||||
onEnd;
|
||||
|
||||
obj.on('data', onData = function (data, encoding) {
|
||||
events.push(['data', data, encoding]);
|
||||
});
|
||||
|
||||
obj.on('end', onEnd = function (data, encoding) {
|
||||
events.push(['end', data, encoding]);
|
||||
});
|
||||
|
||||
return {
|
||||
end: function () {
|
||||
obj.removeListener('data', onData);
|
||||
obj.removeListener('end', onEnd);
|
||||
},
|
||||
destroy: function () {
|
||||
this.end();
|
||||
this.resume = function () {
|
||||
console.error("Cannot resume buffer after destroying it.");
|
||||
};
|
||||
|
||||
onData = onEnd = events = obj = null;
|
||||
},
|
||||
resume: function () {
|
||||
this.end();
|
||||
for (var i = 0, len = events.length; i < len; ++i) {
|
||||
obj.emit.apply(obj, events[i]);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
//
|
||||
// ### function getMaxSockets ()
|
||||
// Returns the maximum number of sockets
|
||||
// allowed on __every__ outgoing request
|
||||
// made by __all__ instances of `HttpProxy`
|
||||
//
|
||||
exports.getMaxSockets = function () {
|
||||
return maxSockets;
|
||||
};
|
||||
|
||||
//
|
||||
// ### function setMaxSockets ()
|
||||
// Sets the maximum number of sockets
|
||||
// allowed on __every__ outgoing request
|
||||
// made by __all__ instances of `HttpProxy`
|
||||
//
|
||||
exports.setMaxSockets = function (value) {
|
||||
maxSockets = value;
|
||||
};
|
||||
|
||||
//
|
||||
// ### function stack (middlewares, proxy)
|
||||
// #### @middlewares {Array} Array of functions to stack.
|
||||
// #### @proxy {HttpProxy|RoutingProxy} Proxy instance to
|
||||
// Iteratively build up a single handler to the `http.Server`
|
||||
// `request` event (i.e. `function (req, res)`) by wrapping
|
||||
// each middleware `layer` into a `child` middleware which
|
||||
// is in invoked by the parent (i.e. predecessor in the Array).
|
||||
//
|
||||
// adapted from https://github.com/creationix/stack
|
||||
//
|
||||
exports.stack = function stack (middlewares, proxy) {
|
||||
var handle;
|
||||
middlewares.reverse().forEach(function (layer) {
|
||||
var child = handle;
|
||||
handle = function (req, res) {
|
||||
var next = function (err) {
|
||||
if (err) {
|
||||
if (res._headerSent) {
|
||||
res.destroy();
|
||||
}
|
||||
else {
|
||||
res.statusCode = 500;
|
||||
res.setHeader('Content-Type', 'text/plain');
|
||||
res.end('Internal Server Error');
|
||||
}
|
||||
|
||||
console.error('Error in middleware(s): %s', err.stack);
|
||||
return;
|
||||
}
|
||||
|
||||
if (child) {
|
||||
child(req, res);
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
// Set the prototype of the `next` function to the instance
|
||||
// of the `proxy` so that in can be used interchangably from
|
||||
// a `connect` style callback and a true `HttpProxy` object.
|
||||
//
|
||||
// e.g. `function (req, res, next)` vs. `function (req, res, proxy)`
|
||||
//
|
||||
next.__proto__ = proxy;
|
||||
layer(req, res, next);
|
||||
};
|
||||
});
|
||||
|
||||
return handle;
|
||||
};
|
||||
|
||||
//
|
||||
// ### function _getAgent (host, port, secure)
|
||||
// #### @options {Object} Options to use when creating the agent.
|
||||
//
|
||||
// {
|
||||
// host: 'localhost',
|
||||
// port: 9000,
|
||||
// https: true,
|
||||
// maxSockets: 100
|
||||
// }
|
||||
//
|
||||
// Createsan agent from the `http` or `https` module
|
||||
// and sets the `maxSockets` property appropriately.
|
||||
//
|
||||
exports._getAgent = function _getAgent (options) {
|
||||
if (!options || !options.host) {
|
||||
throw new Error('`options.host` is required to create an Agent.');
|
||||
}
|
||||
|
||||
if (!options.port) {
|
||||
options.port = options.https ? 443 : 80;
|
||||
}
|
||||
|
||||
var Agent = options.https ? https.Agent : http.Agent,
|
||||
agent;
|
||||
|
||||
agent = new Agent({
|
||||
host: options.host,
|
||||
port: options.port
|
||||
});
|
||||
|
||||
agent.maxSockets = options.maxSockets || maxSockets;
|
||||
|
||||
return agent;
|
||||
}
|
||||
|
||||
//
|
||||
// ### function _getProtocol (options)
|
||||
// #### @options {Object} Options for the proxy target.
|
||||
// Returns the appropriate node.js core protocol module (i.e. `http` or `https`)
|
||||
// based on the `options` supplied.
|
||||
//
|
||||
exports._getProtocol = function _getProtocol (options) {
|
||||
return options.https ? https : http;
|
||||
};
|
||||
|
||||
|
||||
//
|
||||
// ### function _getBase (options)
|
||||
// #### @options {Object} Options for the proxy target.
|
||||
// Returns the relevate base object to create on outgoing proxy request.
|
||||
// If `options.https` are supplied, this function respond with an object
|
||||
// containing the relevant `ca`, `key`, and `cert` properties.
|
||||
//
|
||||
exports._getBase = function _getBase (options) {
|
||||
var result = function () {};
|
||||
|
||||
if (options.https && typeof options.https === 'object') {
|
||||
['ca', 'cert', 'key'].forEach(function (key) {
|
||||
if (options.https[key]) {
|
||||
result.prototype[key] = options.https[key];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
@ -1,772 +0,0 @@
|
||||
/*
|
||||
node-http-proxy.js: http proxy for node.js
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Marak Squires, Fedor Indutny
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
var events = require('events'),
|
||||
util = require('util'),
|
||||
httpProxy = require('../node-http-proxy');
|
||||
|
||||
//
|
||||
// ### function HttpProxy (options)
|
||||
// #### @options {Object} Options for this instance.
|
||||
// Constructor function for new instances of HttpProxy responsible
|
||||
// for managing the life-cycle of streaming reverse proxyied HTTP requests.
|
||||
//
|
||||
// Example options:
|
||||
//
|
||||
// {
|
||||
// target: {
|
||||
// host: 'localhost',
|
||||
// port: 9000
|
||||
// },
|
||||
// forward: {
|
||||
// host: 'localhost',
|
||||
// port: 9001
|
||||
// }
|
||||
// }
|
||||
//
|
||||
var HttpProxy = exports.HttpProxy = function (options) {
|
||||
if (!options || !options.target) {
|
||||
throw new Error('Both `options` and `options.target` are required.');
|
||||
}
|
||||
|
||||
events.EventEmitter.call(this);
|
||||
|
||||
var self = this;
|
||||
|
||||
//
|
||||
// Setup basic proxying options:
|
||||
//
|
||||
// * forward {Object} Options for a forward-proxy (if-any)
|
||||
// * target {Object} Options for the **sole** proxy target of this instance
|
||||
//
|
||||
this.forward = options.forward;
|
||||
this.target = options.target;
|
||||
|
||||
//
|
||||
// Setup the necessary instances instance variables for
|
||||
// the `target` and `forward` `host:port` combinations
|
||||
// used by this instance.
|
||||
//
|
||||
// * agent {http[s].Agent} Agent to be used by this instance.
|
||||
// * protocol {http|https} Core node.js module to make requests with.
|
||||
// * base {Object} Base object to create when proxying containing any https settings.
|
||||
//
|
||||
function setupProxy (key) {
|
||||
self[key].agent = httpProxy._getAgent(self[key]);
|
||||
self[key].protocol = httpProxy._getProtocol(self[key]);
|
||||
self[key].base = httpProxy._getBase(self[key]);
|
||||
}
|
||||
|
||||
setupProxy('target');
|
||||
if (this.forward) {
|
||||
setupProxy('forward');
|
||||
}
|
||||
|
||||
//
|
||||
// Setup opt-in features
|
||||
//
|
||||
this.enable = options.enable || {};
|
||||
this.enable.xforward = typeof this.enable.xforward === 'boolean'
|
||||
? this.enable.xforward
|
||||
: true;
|
||||
|
||||
//
|
||||
// Setup additional options for WebSocket proxying. When forcing
|
||||
// the WebSocket handshake to change the `sec-websocket-location`
|
||||
// and `sec-websocket-origin` headers `options.source` **MUST**
|
||||
// be provided or the operation will fail with an `origin mismatch`
|
||||
// by definition.
|
||||
//
|
||||
this.source = options.source || { host: 'localhost', port: 8000 };
|
||||
this.source.https = this.source.https || options.https;
|
||||
this.changeOrigin = options.changeOrigin || false;
|
||||
};
|
||||
|
||||
// Inherit from events.EventEmitter
|
||||
util.inherits(HttpProxy, events.EventEmitter);
|
||||
|
||||
//
|
||||
// ### function proxyRequest (req, res, [port, host, paused])
|
||||
// #### @req {ServerRequest} Incoming HTTP Request to proxy.
|
||||
// #### @res {ServerResponse} Outgoing HTTP Request to write proxied data to.
|
||||
// #### @buffer {Object} Result from `httpProxy.buffer(req)`
|
||||
//
|
||||
HttpProxy.prototype.proxyRequest = function (req, res, buffer) {
|
||||
var self = this,
|
||||
errState = false,
|
||||
outgoing = new(this.target.base),
|
||||
reverseProxy;
|
||||
|
||||
//
|
||||
// Add common proxy headers to the request so that they can
|
||||
// be availible to the proxy target server:
|
||||
//
|
||||
// * `x-forwarded-for`: IP Address of the original request
|
||||
// * `x-forwarded-proto`: Protocol of the original request
|
||||
// * `x-forwarded-port`: Port of the original request.
|
||||
//
|
||||
|
||||
if (this.enable.xforward && req.connection && req.socket) {
|
||||
req.headers['x-forwarded-for'] = req.connection.remoteAddress || req.socket.remoteAddress;
|
||||
req.headers['x-forwarded-port'] = req.connection.remotePort || req.socket.remotePort;
|
||||
req.headers['x-forwarded-proto'] = req.connection.pair ? 'https' : 'http';
|
||||
}
|
||||
|
||||
//
|
||||
// Emit the `start` event indicating that we have begun the proxy operation.
|
||||
//
|
||||
this.emit('start', req, res, this.target);
|
||||
|
||||
//
|
||||
// If forwarding is enabled for this instance, foward proxy the
|
||||
// specified request to the address provided in `this.forward`
|
||||
//
|
||||
if (this.forward) {
|
||||
this.emit('forward', req, res, this.forward);
|
||||
this._forwardRequest(req);
|
||||
}
|
||||
|
||||
//
|
||||
// #### function proxyError (err)
|
||||
// #### @err {Error} Error contacting the proxy target
|
||||
// Short-circuits `res` in the event of any error when
|
||||
// contacting the proxy target at `host` / `port`.
|
||||
//
|
||||
function proxyError(err) {
|
||||
errState = true;
|
||||
|
||||
//
|
||||
// Emit an `error` event, allowing the application to use custom
|
||||
// error handling. The error handler should end the response.
|
||||
//
|
||||
if (self.emit('proxyError', err, req, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(500, { 'Content-Type': 'text/plain' });
|
||||
|
||||
if (req.method !== 'HEAD') {
|
||||
//
|
||||
// This NODE_ENV=production behavior is mimics Express and
|
||||
// Connect.
|
||||
//
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
res.write('Internal Server Error');
|
||||
}
|
||||
else {
|
||||
res.write('An error has occurred: ' + JSON.stringify(err));
|
||||
}
|
||||
}
|
||||
|
||||
try { res.end() }
|
||||
catch (ex) { console.error("res.end error: %s", ex.message) }
|
||||
}
|
||||
|
||||
//
|
||||
// Setup outgoing proxy with relevant properties.
|
||||
//
|
||||
outgoing.host = this.target.host;
|
||||
outgoing.port = this.target.port;
|
||||
outgoing.agent = this.target.agent;
|
||||
outgoing.method = req.method;
|
||||
outgoing.path = req.url;
|
||||
outgoing.headers = req.headers;
|
||||
|
||||
//
|
||||
// Open new HTTP request to internal resource with will act
|
||||
// as a reverse proxy pass
|
||||
//
|
||||
reverseProxy = this.target.protocol.request(outgoing, function (response) {
|
||||
//
|
||||
// Process the `reverseProxy` `response` when it's received.
|
||||
//
|
||||
if (response.headers.connection) {
|
||||
if (req.headers.connection) { response.headers.connection = req.headers.connection }
|
||||
else { response.headers.connection = 'close' }
|
||||
}
|
||||
|
||||
// Set the headers of the client response
|
||||
res.writeHead(response.statusCode, response.headers);
|
||||
|
||||
// If `response.statusCode === 304`: No 'data' event and no 'end'
|
||||
if (response.statusCode === 304) {
|
||||
try { res.end() }
|
||||
catch (ex) { console.error("res.end error: %s", ex.message) }
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// For each data `chunk` received from the `reverseProxy`
|
||||
// `response` write it to the outgoing `res`.
|
||||
// If the res socket has been killed already, then write()
|
||||
// will throw. Nevertheless, try our best to end it nicely.
|
||||
//
|
||||
response.on('data', function (chunk) {
|
||||
if (req.method !== 'HEAD' && res.writable) {
|
||||
try {
|
||||
var flushed = res.write(chunk);
|
||||
}
|
||||
catch (ex) {
|
||||
console.error("res.write error: %s", ex.message);
|
||||
|
||||
try { res.end() }
|
||||
catch (ex) { console.error("res.end error: %s", ex.message) }
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!flushed) {
|
||||
response.pause();
|
||||
res.once('drain', function () {
|
||||
try { response.resume() }
|
||||
catch (er) { console.error("response.resume error: %s", er.message) }
|
||||
});
|
||||
|
||||
//
|
||||
// Force the `drain` event in 100ms if it hasn't
|
||||
// happened on its own.
|
||||
//
|
||||
setTimeout(function () {
|
||||
res.emit('drain');
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//
|
||||
// When the `reverseProxy` `response` ends, end the
|
||||
// corresponding outgoing `res` unless we have entered
|
||||
// an error state. In which case, assume `res.end()` has
|
||||
// already been called and the 'error' event listener
|
||||
// removed.
|
||||
//
|
||||
response.on('end', function () {
|
||||
if (!errState) {
|
||||
reverseProxy.removeListener('error', proxyError);
|
||||
|
||||
try { res.end() }
|
||||
catch (ex) { console.error("res.end error: %s", ex.message) }
|
||||
|
||||
// Emit the `end` event now that we have completed proxying
|
||||
self.emit('end', req, res);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
//
|
||||
// Handle 'error' events from the `reverseProxy`.
|
||||
//
|
||||
reverseProxy.once('error', proxyError);
|
||||
|
||||
//
|
||||
// For each data `chunk` received from the incoming
|
||||
// `req` write it to the `reverseProxy` request.
|
||||
//
|
||||
req.on('data', function (chunk) {
|
||||
if (!errState) {
|
||||
var flushed = reverseProxy.write(chunk);
|
||||
if (!flushed) {
|
||||
req.pause();
|
||||
reverseProxy.once('drain', function () {
|
||||
try { req.resume() }
|
||||
catch (er) { console.error("req.resume error: %s", er.message) }
|
||||
});
|
||||
|
||||
//
|
||||
// Force the `drain` event in 100ms if it hasn't
|
||||
// happened on its own.
|
||||
//
|
||||
setTimeout(function () {
|
||||
reverseProxy.emit('drain');
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//
|
||||
// When the incoming `req` ends, end the corresponding `reverseProxy`
|
||||
// request unless we have entered an error state.
|
||||
//
|
||||
req.on('end', function () {
|
||||
if (!errState) {
|
||||
reverseProxy.end();
|
||||
}
|
||||
});
|
||||
|
||||
//
|
||||
// If we have been passed buffered data, resume it.
|
||||
//
|
||||
if (buffer) {
|
||||
return !errState
|
||||
? buffer.resume()
|
||||
: buffer.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
// ### function proxyWebSocketRequest (req, socket, head, buffer)
|
||||
// #### @req {ServerRequest} Websocket request to proxy.
|
||||
// #### @socket {net.Socket} Socket for the underlying HTTP request
|
||||
// #### @head {string} Headers for the Websocket request.
|
||||
// #### @buffer {Object} Result from `httpProxy.buffer(req)`
|
||||
// Performs a WebSocket proxy operation to the location specified by
|
||||
// `this.target`.
|
||||
//
|
||||
HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, head, buffer) {
|
||||
var self = this,
|
||||
outgoing = new(this.target.base),
|
||||
listeners = {},
|
||||
errState = false,
|
||||
CRLF = '\r\n';
|
||||
|
||||
//
|
||||
// WebSocket requests must have the `GET` method and
|
||||
// the `upgrade:websocket` header
|
||||
//
|
||||
if (req.method !== 'GET' || req.headers.upgrade.toLowerCase() !== 'websocket') {
|
||||
//
|
||||
// This request is not WebSocket request
|
||||
//
|
||||
return socket.destroy();
|
||||
}
|
||||
|
||||
//
|
||||
// Add common proxy headers to the request so that they can
|
||||
// be availible to the proxy target server:
|
||||
//
|
||||
// * `x-forwarded-for`: IP Address of the original request
|
||||
// * `x-forwarded-proto`: Protocol of the original request
|
||||
// * `x-forwarded-port`: Port of the original request.
|
||||
//
|
||||
if (this.enable.xforward && req.connection && req.connection.socket) {
|
||||
req.headers['x-forwarded-for'] = req.connection.remoteAddress || req.connection.socket.remoteAddress;
|
||||
req.headers['x-forwarded-port'] = req.connection.remotePort || req.connection.socket.remotePort;
|
||||
req.headers['x-forwarded-proto'] = req.connection.pair ? 'https' : 'http';
|
||||
}
|
||||
|
||||
//
|
||||
// Helper function for setting appropriate socket values:
|
||||
// 1. Turn of all bufferings
|
||||
// 2. For server set KeepAlive
|
||||
// 3. For client set encoding
|
||||
//
|
||||
function _socket(socket, keepAlive) {
|
||||
socket.setTimeout(0);
|
||||
socket.setNoDelay(true);
|
||||
|
||||
if (keepAlive) {
|
||||
if (socket.setKeepAlive) {
|
||||
socket.setKeepAlive(true, 0);
|
||||
}
|
||||
else if (socket.pair.cleartext.socket.setKeepAlive) {
|
||||
socket.pair.cleartext.socket.setKeepAlive(true, 0);
|
||||
}
|
||||
}
|
||||
else {
|
||||
socket.setEncoding('utf8');
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Setup the incoming client socket.
|
||||
//
|
||||
_socket(socket, true);
|
||||
|
||||
//
|
||||
// On `upgrade` from the Agent socket, listen to
|
||||
// the appropriate events.
|
||||
//
|
||||
function onUpgrade (reverseProxy, proxySocket) {
|
||||
if (!reverseProxy) {
|
||||
proxySocket.end();
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Any incoming data on this WebSocket to the proxy target
|
||||
// will be written to the `reverseProxy` socket.
|
||||
//
|
||||
proxySocket.on('data', listeners.onIncoming = function (data) {
|
||||
if (reverseProxy.incoming.socket.writable) {
|
||||
try {
|
||||
self.emit('websocket:outgoing', req, socket, head, data);
|
||||
var flushed = reverseProxy.incoming.socket.write(data);
|
||||
if (!flushed) {
|
||||
proxySocket.pause();
|
||||
reverseProxy.incoming.socket.once('drain', function () {
|
||||
try { proxySocket.resume() }
|
||||
catch (er) { console.error("proxySocket.resume error: %s", er.message) }
|
||||
});
|
||||
|
||||
//
|
||||
// Force the `drain` event in 100ms if it hasn't
|
||||
// happened on its own.
|
||||
//
|
||||
setTimeout(function () {
|
||||
reverseProxy.incoming.socket.emit('drain');
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
detach();
|
||||
reverseProxy.incoming.socket.end();
|
||||
proxySocket.end();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//
|
||||
// Any outgoing data on this Websocket from the proxy target
|
||||
// will be written to the `proxySocket` socket.
|
||||
//
|
||||
reverseProxy.incoming.socket.on('data', listeners.onOutgoing = function (data) {
|
||||
try {
|
||||
self.emit('websocket:incoming', reverseProxy, reverseProxy.incoming, head, data);
|
||||
var flushed = proxySocket.write(data);
|
||||
if (!flushed) {
|
||||
reverseProxy.incoming.socket.pause();
|
||||
proxySocket.once('drain', function () {
|
||||
try { reverseProxy.incoming.socket.resume() }
|
||||
catch (er) { console.error("reverseProxy.incoming.socket.resume error: %s", er.message) }
|
||||
});
|
||||
|
||||
//
|
||||
// Force the `drain` event in 100ms if it hasn't
|
||||
// happened on its own.
|
||||
//
|
||||
setTimeout(function () {
|
||||
proxySocket.emit('drain');
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
detach();
|
||||
proxySocket.end();
|
||||
socket.end();
|
||||
}
|
||||
});
|
||||
|
||||
//
|
||||
// Helper function to detach all event listeners
|
||||
// from `reverseProxy` and `proxySocket`.
|
||||
//
|
||||
function detach() {
|
||||
proxySocket.removeListener('end', listeners.onIncomingClose);
|
||||
proxySocket.removeListener('data', listeners.onIncoming);
|
||||
reverseProxy.incoming.socket.removeListener('end', listeners.onOutgoingClose);
|
||||
reverseProxy.incoming.socket.removeListener('data', listeners.onOutgoing);
|
||||
}
|
||||
|
||||
//
|
||||
// If the incoming `proxySocket` socket closes, then
|
||||
// detach all event listeners.
|
||||
//
|
||||
proxySocket.on('end', listeners.onIncomingClose = function() {
|
||||
reverseProxy.incoming.socket.end();
|
||||
detach();
|
||||
|
||||
// Emit the `end` event now that we have completed proxying
|
||||
self.emit('websocket:end', req, socket, head);
|
||||
});
|
||||
|
||||
//
|
||||
// If the `reverseProxy` socket closes, then detach all
|
||||
// event listeners.
|
||||
//
|
||||
reverseProxy.incoming.socket.on('end', listeners.onOutgoingClose = function() {
|
||||
proxySocket.end();
|
||||
detach();
|
||||
});
|
||||
};
|
||||
|
||||
function getPort (port) {
|
||||
port = port || 80;
|
||||
return port - 80 === 0 ? '' : ':' + port
|
||||
}
|
||||
|
||||
//
|
||||
// Get the protocol, and host for this request and create an instance
|
||||
// of `http.Agent` or `https.Agent` from the pool managed by `node-http-proxy`.
|
||||
//
|
||||
var agent = this.target.agent,
|
||||
protocolName = this.target.https ? 'https' : 'http',
|
||||
portUri = getPort(this.source.port),
|
||||
remoteHost = this.target.host + portUri;
|
||||
|
||||
//
|
||||
// Change headers (if requested).
|
||||
//
|
||||
if (this.changeOrigin) {
|
||||
req.headers.host = remoteHost;
|
||||
req.headers.origin = protocolName + '://' + remoteHost;
|
||||
}
|
||||
|
||||
//
|
||||
// Make the outgoing WebSocket request
|
||||
//
|
||||
outgoing.host = this.target.host;
|
||||
outgoing.port = this.target.port;
|
||||
outgoing.method = 'GET';
|
||||
outgoing.path = req.url;
|
||||
outgoing.headers = req.headers;
|
||||
|
||||
var reverseProxy = agent.appendMessage(outgoing);
|
||||
|
||||
//
|
||||
// On any errors from the `reverseProxy` emit the
|
||||
// `webSocketProxyError` and close the appropriate
|
||||
// connections.
|
||||
//
|
||||
function proxyError (err) {
|
||||
reverseProxy.end();
|
||||
if (self.emit('webSocketProxyError', req, socket, head)) {
|
||||
return;
|
||||
}
|
||||
|
||||
socket.end();
|
||||
}
|
||||
|
||||
//
|
||||
// Here we set the incoming `req`, `socket` and `head` data to the outgoing
|
||||
// request so that we can reuse this data later on in the closure scope
|
||||
// available to the `upgrade` event. This bookkeeping is not tracked anywhere
|
||||
// in nodejs core and is **very** specific to proxying WebSockets.
|
||||
//
|
||||
reverseProxy.agent = agent;
|
||||
reverseProxy.incoming = {
|
||||
request: req,
|
||||
socket: socket,
|
||||
head: head
|
||||
};
|
||||
|
||||
//
|
||||
// If the agent for this particular `host` and `port` combination
|
||||
// is not already listening for the `upgrade` event, then do so once.
|
||||
// This will force us not to disconnect.
|
||||
//
|
||||
// In addition, it's important to note the closure scope here. Since
|
||||
// there is no mapping of the socket to the request bound to it.
|
||||
//
|
||||
if (!agent._events || agent._events['upgrade'].length === 0) {
|
||||
agent.on('upgrade', function (_, remoteSocket, head) {
|
||||
//
|
||||
// Prepare the socket for the reverseProxy request and begin to
|
||||
// stream data between the two sockets. Here it is important to
|
||||
// note that `remoteSocket._httpMessage === reverseProxy`.
|
||||
//
|
||||
_socket(remoteSocket, true);
|
||||
onUpgrade(remoteSocket._httpMessage, remoteSocket);
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// If the reverseProxy connection has an underlying socket,
|
||||
// then execute the WebSocket handshake.
|
||||
//
|
||||
if (typeof reverseProxy.socket !== 'undefined') {
|
||||
reverseProxy.socket.on('data', function handshake (data) {
|
||||
//
|
||||
// Ok, kind of harmfull part of code. Socket.IO sends a hash
|
||||
// at the end of handshake if protocol === 76, but we need
|
||||
// to replace 'host' and 'origin' in response so we split
|
||||
// data to printable data and to non-printable. (Non-printable
|
||||
// will come after double-CRLF).
|
||||
//
|
||||
var sdata = data.toString();
|
||||
|
||||
// Get the Printable data
|
||||
sdata = sdata.substr(0, sdata.search(CRLF + CRLF));
|
||||
|
||||
// Get the Non-Printable data
|
||||
data = data.slice(Buffer.byteLength(sdata), data.length);
|
||||
|
||||
if (self.source.https && !self.target.https) {
|
||||
//
|
||||
// If the proxy server is running HTTPS but the client is running
|
||||
// HTTP then replace `ws` with `wss` in the data sent back to the client.
|
||||
//
|
||||
sdata = sdata.replace('ws:', 'wss:');
|
||||
}
|
||||
|
||||
try {
|
||||
//
|
||||
// Write the printable and non-printable data to the socket
|
||||
// from the original incoming request.
|
||||
//
|
||||
self.emit('websocket:handshake', req, socket, head, sdata, data);
|
||||
socket.write(sdata);
|
||||
var flushed = socket.write(data);
|
||||
if (!flushed) {
|
||||
reverseProxy.socket.pause();
|
||||
socket.once('drain', function () {
|
||||
try { reverseProxy.socket.resume() }
|
||||
catch (er) { console.error("reverseProxy.socket.resume error: %s", er.message) }
|
||||
});
|
||||
|
||||
//
|
||||
// Force the `drain` event in 100ms if it hasn't
|
||||
// happened on its own.
|
||||
//
|
||||
setTimeout(function () {
|
||||
socket.emit('drain');
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
//
|
||||
// Remove data listener on socket error because the
|
||||
// 'handshake' has failed.
|
||||
//
|
||||
reverseProxy.socket.removeListener('data', handshake);
|
||||
return proxyError(ex);
|
||||
}
|
||||
|
||||
// Catch socket errors
|
||||
socket.on('error', proxyError);
|
||||
|
||||
//
|
||||
// Remove data listener now that the 'handshake' is complete
|
||||
//
|
||||
reverseProxy.socket.removeListener('data', handshake);
|
||||
});
|
||||
}
|
||||
|
||||
reverseProxy.on('error', proxyError);
|
||||
|
||||
try {
|
||||
//
|
||||
// Attempt to write the upgrade-head to the reverseProxy
|
||||
// request. This is small, and there's only ever one of
|
||||
// it; no need for pause/resume.
|
||||
//
|
||||
// XXX This is very wrong and should be fixed in node's core
|
||||
//
|
||||
reverseProxy.write(head);
|
||||
if (head && head.length === 0) {
|
||||
reverseProxy._send('');
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
return proxyError(ex);
|
||||
}
|
||||
|
||||
//
|
||||
// If we have been passed buffered data, resume it.
|
||||
//
|
||||
if (buffer) {
|
||||
return !errState
|
||||
? buffer.resume()
|
||||
: buffer.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
// ### function close()
|
||||
// Closes all sockets associated with the Agents
|
||||
// belonging to this instance.
|
||||
//
|
||||
HttpProxy.prototype.close = function () {
|
||||
[this.forward, this.target].forEach(function (proxy) {
|
||||
if (proxy && proxy.agent) {
|
||||
proxy.agent.sockets.forEach(function (socket) {
|
||||
socket.end();
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
//
|
||||
// ### @private function _forwardRequest (req)
|
||||
// #### @req {ServerRequest} Incoming HTTP Request to proxy.
|
||||
// Forwards the specified `req` to the location specified
|
||||
// by `this.forward` ignoring errors and the subsequent response.
|
||||
//
|
||||
HttpProxy.prototype._forwardRequest = function (req) {
|
||||
var self = this,
|
||||
outgoing = new(this.forward.base),
|
||||
forwardProxy;
|
||||
|
||||
//
|
||||
// Setup outgoing proxy with relevant properties.
|
||||
//
|
||||
outgoing.host = this.forward.host;
|
||||
outgoing.port = this.forward.port,
|
||||
outgoing.agent = this.forward.agent;
|
||||
outgoing.method = req.method;
|
||||
outgoing.path = req.url;
|
||||
outgoing.headers = req.headers;
|
||||
|
||||
//
|
||||
// Open new HTTP request to internal resource with will
|
||||
// act as a reverse proxy pass.
|
||||
//
|
||||
forwardProxy = this.forward.protocol.request(outgoing, function (response) {
|
||||
//
|
||||
// Ignore the response from the forward proxy since this is a 'fire-and-forget' proxy.
|
||||
// Remark (indexzero): We will eventually emit a 'forward' event here for performance tuning.
|
||||
//
|
||||
});
|
||||
|
||||
//
|
||||
// Add a listener for the connection timeout event.
|
||||
//
|
||||
// Remark: Ignoring this error in the event
|
||||
// forward target doesn't exist.
|
||||
//
|
||||
forwardProxy.once('error', function (err) { });
|
||||
|
||||
//
|
||||
// Chunk the client request body as chunks from
|
||||
// the proxied request come in
|
||||
//
|
||||
req.on('data', function (chunk) {
|
||||
var flushed = forwardProxy.write(chunk);
|
||||
if (!flushed) {
|
||||
req.pause();
|
||||
forwardProxy.once('drain', function () {
|
||||
try { req.resume() }
|
||||
catch (er) { console.error("req.resume error: %s", er.message) }
|
||||
});
|
||||
|
||||
//
|
||||
// Force the `drain` event in 100ms if it hasn't
|
||||
// happened on its own.
|
||||
//
|
||||
setTimeout(function () {
|
||||
forwardProxy.emit('drain');
|
||||
}, 100);
|
||||
}
|
||||
});
|
||||
|
||||
//
|
||||
// At the end of the client request, we are going to
|
||||
// stop the proxied request
|
||||
//
|
||||
req.on('end', function () {
|
||||
forwardProxy.end();
|
||||
});
|
||||
};
|
||||
@ -1,165 +0,0 @@
|
||||
/*
|
||||
node-http-proxy.js: Lookup table for proxy targets in node.js
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
var util = require('util'),
|
||||
events = require('events'),
|
||||
fs = require('fs');
|
||||
|
||||
//
|
||||
// ### function ProxyTable (router, silent)
|
||||
// #### @router {Object} Object containing the host based routes
|
||||
// #### @silent {Boolean} Value indicating whether we should suppress logs
|
||||
// #### @hostnameOnly {Boolean} Value indicating if we should route based on __hostname string only__
|
||||
// Constructor function for the ProxyTable responsible for getting
|
||||
// locations of proxy targets based on ServerRequest headers; specifically
|
||||
// the HTTP host header.
|
||||
//
|
||||
var ProxyTable = exports.ProxyTable = function (options) {
|
||||
events.EventEmitter.call(this);
|
||||
|
||||
this.silent = options.silent || options.silent !== true;
|
||||
this.hostnameOnly = options.hostnameOnly === true;
|
||||
|
||||
if (typeof options.router === 'object') {
|
||||
//
|
||||
// If we are passed an object literal setup
|
||||
// the routes with RegExps from the router
|
||||
//
|
||||
this.setRoutes(options.router);
|
||||
}
|
||||
else if (typeof options.router === 'string') {
|
||||
//
|
||||
// If we are passed a string then assume it is a
|
||||
// file path, parse that file and watch it for changes
|
||||
//
|
||||
var self = this;
|
||||
this.routeFile = options.router;
|
||||
this.setRoutes(JSON.parse(fs.readFileSync(options.router)).router);
|
||||
|
||||
fs.watchFile(this.routeFile, function () {
|
||||
fs.readFile(self.routeFile, function (err, data) {
|
||||
if (err) {
|
||||
self.emit('error', err);
|
||||
}
|
||||
|
||||
self.setRoutes(JSON.parse(data).router);
|
||||
self.emit('routes', self.hostnameOnly === false ? self.routes : self.router);
|
||||
});
|
||||
});
|
||||
}
|
||||
else {
|
||||
throw new Error('Cannot parse router with unknown type: ' + typeof router);
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
// Inherit from `events.EventEmitter`
|
||||
//
|
||||
util.inherits(ProxyTable, events.EventEmitter);
|
||||
|
||||
//
|
||||
// ### function setRoutes (router)
|
||||
// #### @router {Object} Object containing the host based routes
|
||||
// Sets the host-based routes to be used by this instance.
|
||||
//
|
||||
ProxyTable.prototype.setRoutes = function (router) {
|
||||
if (!router) {
|
||||
throw new Error('Cannot update ProxyTable routes without router.');
|
||||
}
|
||||
|
||||
this.router = router;
|
||||
|
||||
if (this.hostnameOnly === false) {
|
||||
var self = this;
|
||||
this.routes = [];
|
||||
|
||||
Object.keys(router).forEach(function (path) {
|
||||
var route = new RegExp(path, 'i');
|
||||
|
||||
self.routes.push({
|
||||
route: route,
|
||||
target: router[path]
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
// ### function getProxyLocation (req)
|
||||
// #### @req {ServerRequest} The incoming server request to get proxy information about.
|
||||
// Returns the proxy location based on the HTTP Headers in the ServerRequest `req`
|
||||
// available to this instance.
|
||||
//
|
||||
ProxyTable.prototype.getProxyLocation = function (req) {
|
||||
if (!req || !req.headers || !req.headers.host) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var target = req.headers.host.split(':')[0];
|
||||
if (this.hostnameOnly == true) {
|
||||
if (this.router.hasOwnProperty(target)) {
|
||||
var location = this.router[target].split(':'),
|
||||
host = location[0],
|
||||
port = location.length === 1 ? 80 : location[1];
|
||||
|
||||
return {
|
||||
port: port,
|
||||
host: host
|
||||
};
|
||||
}
|
||||
}
|
||||
else {
|
||||
target += req.url;
|
||||
for (var i in this.routes) {
|
||||
var route = this.routes[i],
|
||||
match;
|
||||
|
||||
if (match = target.match(route.route)) {
|
||||
var location = route.target.split(':'),
|
||||
host = location[0],
|
||||
port = location.length === 1 ? 80 : location[1];
|
||||
|
||||
return {
|
||||
port: port,
|
||||
host: host
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
//
|
||||
// ### close function ()
|
||||
// Cleans up the event listeneners maintained
|
||||
// by this instance.
|
||||
//
|
||||
ProxyTable.prototype.close = function () {
|
||||
if (typeof this.routeFile === 'string') {
|
||||
fs.unwatchFile(this.routeFile);
|
||||
}
|
||||
};
|
||||
@ -1,250 +0,0 @@
|
||||
/*
|
||||
* routing-proxy.js: A routing proxy consuming a RoutingTable and multiple HttpProxy instances
|
||||
*
|
||||
* (C) 2011 Nodejitsu Inc.
|
||||
* MIT LICENCE
|
||||
*
|
||||
*/
|
||||
|
||||
var events = require('events'),
|
||||
util = require('util'),
|
||||
HttpProxy = require('./http-proxy').HttpProxy,
|
||||
ProxyTable = require('./proxy-table').ProxyTable;
|
||||
|
||||
//
|
||||
// ### function RoutingProxy (options)
|
||||
// #### @options {Object} Options for this instance
|
||||
// Constructor function for the RoutingProxy object, a higher level
|
||||
// reverse proxy Object which can proxy to multiple hosts and also interface
|
||||
// easily with a RoutingTable instance.
|
||||
//
|
||||
var RoutingProxy = exports.RoutingProxy = function (options) {
|
||||
events.EventEmitter.call(this);
|
||||
|
||||
var self = this;
|
||||
options = options || {};
|
||||
|
||||
if (options.router) {
|
||||
this.proxyTable = new ProxyTable(options);
|
||||
this.proxyTable.on('routes', function (routes) {
|
||||
self.emit('routes', routes);
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Create a set of `HttpProxy` objects to be used later on calls
|
||||
// to `.proxyRequest()` and `.proxyWebSocketRequest()`.
|
||||
//
|
||||
this.proxies = {};
|
||||
|
||||
//
|
||||
// Setup default target options (such as `https`).
|
||||
//
|
||||
this.target = {};
|
||||
this.target.https = options.target && options.target.https;
|
||||
|
||||
//
|
||||
// Setup other default options to be used for instances of
|
||||
// `HttpProxy` created by this `RoutingProxy` instance.
|
||||
//
|
||||
this.source = options.source || { host: 'localhost', port: 8000 };
|
||||
this.https = this.source.https || options.https;
|
||||
this.enable = options.enable;
|
||||
this.forward = options.forward;
|
||||
};
|
||||
|
||||
|
||||
//
|
||||
// Inherit from `events.EventEmitter`.
|
||||
//
|
||||
util.inherits(RoutingProxy, events.EventEmitter);
|
||||
|
||||
//
|
||||
// ### function add (options)
|
||||
// #### @options {Object} Options for the `HttpProxy` to add.
|
||||
// Adds a new instance of `HttpProxy` to this `RoutingProxy` instance
|
||||
// for the specified `options.host` and `options.port`.
|
||||
//
|
||||
RoutingProxy.prototype.add = function (options) {
|
||||
var self = this,
|
||||
key = this._getKey(options);
|
||||
|
||||
//
|
||||
// TODO: Consume properties in `options` related to the `ProxyTable`.
|
||||
//
|
||||
options.target = options.target || {};
|
||||
options.target.host = options.target.host || options.host;
|
||||
options.target.port = options.target.port || options.port;
|
||||
options.target.https = this.target && this.target.https ||
|
||||
options.target && options.target.https ||
|
||||
options.https;
|
||||
|
||||
//
|
||||
// Setup options to pass-thru to the new `HttpProxy` instance
|
||||
// for the specified `options.host` and `options.port` pair.
|
||||
//
|
||||
['https', 'enable', 'forward'].forEach(function (key) {
|
||||
if (options[key] !== false && self[key]) {
|
||||
options[key] = self[key];
|
||||
}
|
||||
});
|
||||
|
||||
this.proxies[key] = new HttpProxy(options);
|
||||
this.proxies[key].on('proxyError', this.emit.bind(this, 'proxyError'));
|
||||
this.proxies[key].on('webSocketProxyError', this.emit.bind(this, 'webSocketProxyError'));
|
||||
};
|
||||
|
||||
//
|
||||
// ### function remove (options)
|
||||
// #### @options {Object} Options mapping to the `HttpProxy` to remove.
|
||||
// Removes an instance of `HttpProxy` from this `RoutingProxy` instance
|
||||
// for the specified `options.host` and `options.port` (if they exist).
|
||||
//
|
||||
RoutingProxy.prototype.remove = function (options) {
|
||||
var key = this._getKey(options);
|
||||
};
|
||||
|
||||
//
|
||||
// ### function close()
|
||||
// Cleans up any state left behind (sockets, timeouts, etc)
|
||||
// associated with this instance.
|
||||
//
|
||||
RoutingProxy.prototype.close = function () {
|
||||
var self = this;
|
||||
|
||||
if (this.proxyTable) {
|
||||
//
|
||||
// Close the `RoutingTable` associated with
|
||||
// this instance (if any).
|
||||
//
|
||||
this.proxyTable.close();
|
||||
}
|
||||
|
||||
//
|
||||
// Close all sockets for all `HttpProxy` object(s)
|
||||
// associated with this instance.
|
||||
//
|
||||
Object.keys(this.proxies).forEach(function (key) {
|
||||
self.proxies[key].close();
|
||||
});
|
||||
};
|
||||
|
||||
//
|
||||
// ### function proxyRequest (req, res, [port, host, paused])
|
||||
// #### @req {ServerRequest} Incoming HTTP Request to proxy.
|
||||
// #### @res {ServerResponse} Outgoing HTTP Request to write proxied data to.
|
||||
// #### @options {Object} Options for the outgoing proxy request.
|
||||
//
|
||||
// options.port {number} Port to use on the proxy target host.
|
||||
// options.host {string} Host of the proxy target.
|
||||
// options.buffer {Object} Result from `httpProxy.buffer(req)`
|
||||
// options.https {Object|boolean} Settings for https.
|
||||
//
|
||||
RoutingProxy.prototype.proxyRequest = function (req, res, options) {
|
||||
options = options || {};
|
||||
|
||||
//
|
||||
// Check the proxy table for this instance to see if we need
|
||||
// to get the proxy location for the request supplied. We will
|
||||
// always ignore the proxyTable if an explicit `port` and `host`
|
||||
// arguments are supplied to `proxyRequest`.
|
||||
//
|
||||
if (this.proxyTable && !options.host) {
|
||||
location = this.proxyTable.getProxyLocation(req);
|
||||
|
||||
//
|
||||
// If no location is returned from the ProxyTable instance
|
||||
// then respond with `404` since we do not have a valid proxy target.
|
||||
//
|
||||
if (!location) {
|
||||
try {
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
}
|
||||
catch (er) {
|
||||
console.error("res.writeHead/res.end error: %s", er.message);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// When using the ProxyTable in conjunction with an HttpProxy instance
|
||||
// only the following arguments are valid:
|
||||
//
|
||||
// * `proxy.proxyRequest(req, res, { host: 'localhost' })`: This will be skipped
|
||||
// * `proxy.proxyRequest(req, res, { buffer: buffer })`: Buffer will get updated appropriately
|
||||
// * `proxy.proxyRequest(req, res)`: Options will be assigned appropriately.
|
||||
//
|
||||
options.port = location.port;
|
||||
options.host = location.host;
|
||||
}
|
||||
|
||||
var key = options.host + ':' + options.port,
|
||||
proxy;
|
||||
|
||||
if (!this.proxies[key]) {
|
||||
this.add(options);
|
||||
|
||||
}
|
||||
|
||||
proxy = this.proxies[key];
|
||||
proxy.proxyRequest(req, res, options.buffer);
|
||||
};
|
||||
|
||||
//
|
||||
// ### function proxyWebSocketRequest (req, socket, head, options)
|
||||
// #### @req {ServerRequest} Websocket request to proxy.
|
||||
// #### @socket {net.Socket} Socket for the underlying HTTP request
|
||||
// #### @head {string} Headers for the Websocket request.
|
||||
// #### @options {Object} Options to use when proxying this request.
|
||||
//
|
||||
// options.port {number} Port to use on the proxy target host.
|
||||
// options.host {string} Host of the proxy target.
|
||||
// options.buffer {Object} Result from `httpProxy.buffer(req)`
|
||||
// options.https {Object|boolean} Settings for https.
|
||||
//
|
||||
RoutingProxy.prototype.proxyWebSocketRequest = function (req, socket, head, options) {
|
||||
options = options || {};
|
||||
|
||||
if (this.proxyTable && !options.host) {
|
||||
location = this.proxyTable.getProxyLocation(req);
|
||||
|
||||
if (!location) {
|
||||
return socket.destroy();
|
||||
}
|
||||
|
||||
options.port = location.port;
|
||||
options.host = location.host;
|
||||
}
|
||||
|
||||
var key = options.host + ':' + options.port,
|
||||
proxy;
|
||||
|
||||
if (!this.proxies[key]) {
|
||||
this.add(options);
|
||||
}
|
||||
|
||||
proxy = this.proxies[key];
|
||||
proxy.proxyWebSocketRequest(req, socket, head, options.buffer);
|
||||
};
|
||||
|
||||
//
|
||||
// ### @private function _getKey (options)
|
||||
// #### @options {Object} Options to extract the key from
|
||||
// Ensures that the appropriate options are present in the `options`
|
||||
// provided and responds with a string key representing the `host`, `port`
|
||||
// combination contained within.
|
||||
//
|
||||
RoutingProxy.prototype._getKey = function (options) {
|
||||
if (!options || ((!options.host || !options.port)
|
||||
&& (!options.target || !options.target.host || !options.target.port))) {
|
||||
throw new Error('options.host and options.port or options.target are required.');
|
||||
return;
|
||||
}
|
||||
|
||||
return [
|
||||
options.host || options.target.host,
|
||||
options.port || options.target.port
|
||||
].join(':');
|
||||
}
|
||||
2028
package-lock.json
generated
Normal file
2028
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
54
package.json
54
package.json
@ -1,35 +1,41 @@
|
||||
{
|
||||
"name": "http-proxy",
|
||||
"version": "0.7.3",
|
||||
"description": "A full-featured http reverse proxy for node.js",
|
||||
"author": "Charlie Robbins <charlie.robbins@gmail.com>",
|
||||
"contributors": [
|
||||
{ "name": "Mikeal Rogers", "email": "mikeal.rogers@gmail.com" },
|
||||
{ "name": "Marak Squires", "email": "marak.squires@gmail.com" },
|
||||
{ "name": "Fedor Indutny", "email": "fedor.indutny@gmail.com" },
|
||||
{ "name": "Dominic Tarr", "email": "dominic@nodejitsu.com" }
|
||||
],
|
||||
"version": "1.18.1",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "http://github.com/nodejitsu/node-http-proxy.git"
|
||||
"url": "https://github.com/http-party/node-http-proxy.git"
|
||||
},
|
||||
"keywords": ["reverse", "proxy", "http"],
|
||||
"description": "HTTP proxying for the masses",
|
||||
"author": "Charlie Robbins <charlie.robbins@gmail.com>",
|
||||
"maintainers": [
|
||||
"jcrugzz <jcrugzz@gmail.com>"
|
||||
],
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"colors": "0.x.x",
|
||||
"optimist": "0.2.x",
|
||||
"pkginfo": "0.2.x"
|
||||
"eventemitter3": "^4.0.0",
|
||||
"requires-port": "^1.0.0",
|
||||
"follow-redirects": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"request": "1.9.x",
|
||||
"vows": "0.5.x",
|
||||
"socket.io": "0.6.x"
|
||||
"async": "^3.0.0",
|
||||
"auto-changelog": "^1.15.0",
|
||||
"concat-stream": "^2.0.0",
|
||||
"expect.js": "~0.3.1",
|
||||
"mocha": "^3.5.3",
|
||||
"nyc": "^14.0.0",
|
||||
"semver": "^5.0.3",
|
||||
"socket.io": "^2.1.0",
|
||||
"socket.io-client": "^2.1.0",
|
||||
"sse": "0.0.8",
|
||||
"ws": "^3.0.0"
|
||||
},
|
||||
"main": "./lib/node-http-proxy",
|
||||
"bin": { "node-http-proxy": "./bin/node-http-proxy" },
|
||||
"scripts": {
|
||||
"test": "npm run-script test-http && npm run-script test-https",
|
||||
"test-http": "vows --spec && vows --spec --target=secure",
|
||||
"test-https": "vows --spec --source=secure && vows --spec --source=secure --target=secure"
|
||||
"scripts": {
|
||||
"mocha": "mocha test/*-test.js",
|
||||
"test": "nyc --reporter=text --reporter=lcov npm run mocha",
|
||||
"version": "auto-changelog -p && git add CHANGELOG.md"
|
||||
},
|
||||
"engines": { "node": "0.4.x || 0.5.x" }
|
||||
"engines": {
|
||||
"node": ">=8.0.0"
|
||||
},
|
||||
"license": "MIT"
|
||||
}
|
||||
|
||||
19
renovate.json
Normal file
19
renovate.json
Normal file
@ -0,0 +1,19 @@
|
||||
{
|
||||
"platform": "github",
|
||||
"autodiscover": false,
|
||||
"requireConfig": true,
|
||||
"ignoreNpmrcFile": true,
|
||||
"rangeStrategy": "replace",
|
||||
"packageRules": [
|
||||
{
|
||||
"packagePatterns": [
|
||||
"*"
|
||||
],
|
||||
"minor": {
|
||||
"groupName": "all non-major dependencies",
|
||||
"groupSlug": "all-minor-patch"
|
||||
}
|
||||
}
|
||||
],
|
||||
"commitMessagePrefix": "[dist]"
|
||||
}
|
||||
71
test/examples-test.js
Normal file
71
test/examples-test.js
Normal file
@ -0,0 +1,71 @@
|
||||
/*
|
||||
examples-test.js: Test to run all the examples
|
||||
|
||||
Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
|
||||
|
||||
*/
|
||||
var path = require('path'),
|
||||
fs = require('fs'),
|
||||
spawn = require('child_process').spawn,
|
||||
expect = require('expect.js'),
|
||||
async = require('async');
|
||||
|
||||
var rootDir = path.join(__dirname, '..'),
|
||||
examplesDir = path.join(rootDir, 'examples');
|
||||
|
||||
describe.skip('http-proxy examples', function () {
|
||||
describe('Before testing examples', function () {
|
||||
// Set a timeout to avoid this error
|
||||
this.timeout(30 * 1000);
|
||||
it('should have installed dependencies', function (done) {
|
||||
async.waterfall([
|
||||
//
|
||||
// 1. Read files in examples dir
|
||||
//
|
||||
async.apply(fs.readdir, examplesDir),
|
||||
//
|
||||
// 2. If node_modules exists, continue. Otherwise
|
||||
// exec `npm` to install them
|
||||
//
|
||||
function checkNodeModules(files, next) {
|
||||
if (files.indexOf('node_modules') !== -1) {
|
||||
return next();
|
||||
}
|
||||
|
||||
console.log('Warning: installing dependencies, this operation could take a while');
|
||||
|
||||
var child = spawn('npm', ['install', '-f'], {
|
||||
cwd: examplesDir
|
||||
});
|
||||
|
||||
child.on('exit', function (code) {
|
||||
return code
|
||||
? next(new Error('npm install exited with non-zero exit code'))
|
||||
: next();
|
||||
});
|
||||
},
|
||||
//
|
||||
// 3. Read files in examples dir again to ensure the install
|
||||
// worked as expected.
|
||||
//
|
||||
async.apply(fs.readdir, examplesDir),
|
||||
], done);
|
||||
})
|
||||
});
|
||||
|
||||
describe('Requiring all the examples', function () {
|
||||
it('should have no errors', function (done) {
|
||||
async.each(['balancer', 'http', 'middleware', 'websocket'], function (dir, cb) {
|
||||
var name = 'examples/' + dir,
|
||||
files = fs.readdirSync(path.join(rootDir, 'examples', dir));
|
||||
|
||||
async.each(files, function (file, callback) {
|
||||
var example;
|
||||
expect(function () { example = require(path.join(examplesDir, dir, file)); }).to.not.throwException();
|
||||
expect(example).to.be.an('object');
|
||||
callback();
|
||||
}, cb);
|
||||
}, done);
|
||||
})
|
||||
})
|
||||
})
|
||||
34
test/fixtures/agent2-cert.pem
vendored
34
test/fixtures/agent2-cert.pem
vendored
@ -1,13 +1,25 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIB7DCCAZYCCQC7gs0MDNn6MTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJV
|
||||
UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO
|
||||
BgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MjEgMB4GCSqGSIb3DQEJARYR
|
||||
cnlAdGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEy
|
||||
WjB9MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYD
|
||||
VQQKEwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MjEg
|
||||
MB4GCSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwXDANBgkqhkiG9w0BAQEF
|
||||
AANLADBIAkEAyXb8FrRdKbhrKLgLSsn61i1C7w7fVVVd7OQsmV/7p9WB2lWFiDlC
|
||||
WKGU9SiIz/A6wNZDUAuc2E+VwtpCT561AQIDAQABMA0GCSqGSIb3DQEBBQUAA0EA
|
||||
C8HzpuNhFLCI3A5KkBS5zHAQax6TFUOhbpBCR0aTDbJ6F1liDTK1lmU/BjvPoj+9
|
||||
1LHwrmh29rK8kBPEjmymCQ==
|
||||
MIIEIDCCAggCCQChRDh/XiBF+zANBgkqhkiG9w0BAQsFADBUMQswCQYDVQQGEwJ1
|
||||
czETMBEGA1UECAwKV2FzaGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEeMBwGA1UE
|
||||
AwwVRHVtbXkgSW50ZXJtZWRpYXRlIENBMB4XDTE4MDYyMjIwMzEwNFoXDTMyMDIy
|
||||
OTIwMzEwNFowUDELMAkGA1UEBhMCdXMxEzARBgNVBAgMCldhc2hpbmd0b24xEDAO
|
||||
BgNVBAcMB1NlYXR0bGUxGjAYBgNVBAMMEWR1bW15LmV4YW1wbGUuY29tMIIBIjAN
|
||||
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvSQq3d8AeZMTvtqZ13jWCckikyXJ
|
||||
SACvkGCQUCJqOceESbg6IHdRzQdoccE4P3sbvNsf9BlbdJKM+neCxabqKaU1PPje
|
||||
4P0tHT57t6yJrMuUh9NxEz3Bgh1srNHVS7saKvwHmcKm79jc+wxlioPmEQvQagjn
|
||||
y7oTkyLt0sn4LGxBjrcv2JoHOC9f1pxX7l47MaiN0/ctRau7Nr3PFn+pkB4Yf6Z0
|
||||
VyicVJbaUSz39Qo4HQWl1L2hiBP3CS1oKs2Yk0O1aOCMExWrhZQan+ZgHqL1rhgm
|
||||
kPpw2/zwwPt5Vf9CSakvHwg198EXuTTXtkzYduuIJAm8yp969iEIiG2xTwIDAQAB
|
||||
MA0GCSqGSIb3DQEBCwUAA4ICAQBnMSIo+kujkeXPh+iErFBmNtu/7EA+i/QnFPbN
|
||||
lSLngclYYBJAGQI+DhirJI8ghDi6vmlHB2THewDaOJXEKvC1czE8064wioIcA9HJ
|
||||
l3QJ3YYOFRctYdSHBU4TWdJbPgkLWDzYP5smjOfw8nDdr4WO/5jh9qRFcFpTFmQf
|
||||
DyU3xgWLsQnNK3qXLdJjWG75pEhHR+7TGo+Ob/RUho/1RX/P89Ux7/oVbzdKqqFu
|
||||
SErXAsjEIEFzWOM2uDOt6hrxDF6q+8/zudwQNEo422poEcTT9tDEFxMQ391CzZRi
|
||||
nozBm4igRn1f5S3YZzLI6VEUns0s76BNy2CzvFWn40DziTqNBExAMfFFj76wiMsX
|
||||
6fTIdcvkaTBa0S9SZB0vN99qahBdcG17rt4RssMHVRH1Wn7NXMwe476L0yXZ6gO7
|
||||
Z4uNAPxgaI3BRP75EPfslLutCLZ+BC4Zzu6MY0Salbpfl0Go462EhsKCxvYhE2Dg
|
||||
T477pICLfETZfA499Fd1tOaIsoLCrILAia/+Yd76uf94MuXUIqykDng/4H7xCc47
|
||||
BZhNFJiPC6XHaXzN7NYSEUNX9VOwY8ncxKwtP6TXga96PdMUy/p98KIM8RZlDoxB
|
||||
Xy9dcZBFNn/zrqjW7R0CCWCUriDIFSmEP0wDZ91YYa6BVuJMb5uL/USkTLpjZS4/
|
||||
HNGvug==
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
10
test/fixtures/agent2-csr.pem
vendored
10
test/fixtures/agent2-csr.pem
vendored
@ -1,10 +0,0 @@
|
||||
-----BEGIN CERTIFICATE REQUEST-----
|
||||
MIIBXTCCAQcCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMQswCQYDVQQH
|
||||
EwJTRjEPMA0GA1UEChMGSm95ZW50MRAwDgYDVQQLEwdOb2RlLmpzMQ8wDQYDVQQD
|
||||
EwZhZ2VudDIxIDAeBgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMFwwDQYJ
|
||||
KoZIhvcNAQEBBQADSwAwSAJBAMl2/Ba0XSm4ayi4C0rJ+tYtQu8O31VVXezkLJlf
|
||||
+6fVgdpVhYg5QlihlPUoiM/wOsDWQ1ALnNhPlcLaQk+etQECAwEAAaAlMCMGCSqG
|
||||
SIb3DQEJBzEWExRBIGNoYWxsZW5nZSBwYXNzd29yZDANBgkqhkiG9w0BAQUFAANB
|
||||
AJnll2pt5l0pzskQSpjjLVTlFDFmJr/AZ3UK8v0WxBjYjCe5Jx4YehkChpxIyDUm
|
||||
U3J9q9MDUf0+Y2+EGkssFfk=
|
||||
-----END CERTIFICATE REQUEST-----
|
||||
32
test/fixtures/agent2-key.pem
vendored
32
test/fixtures/agent2-key.pem
vendored
@ -1,9 +1,27 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIBOgIBAAJBAMl2/Ba0XSm4ayi4C0rJ+tYtQu8O31VVXezkLJlf+6fVgdpVhYg5
|
||||
QlihlPUoiM/wOsDWQ1ALnNhPlcLaQk+etQECAwEAAQJBAMT6Bf34+UHKY1ObpsbH
|
||||
9u2jsVblFq1rWvs8GPMY6oertzvwm3DpuSUp7PTgOB1nLTLYtCERbQ4ovtN8tn3p
|
||||
OHUCIQDzIEGsoCr5vlxXvy2zJwu+fxYuhTZWMVuo1397L0VyhwIhANQh+yzqUgaf
|
||||
WRtSB4T2W7ADtJI35ET61jKBty3CqJY3AiAIwju7dVW3A5WeD6Qc1SZGKZvp9yCb
|
||||
AFI2BfVwwaY11wIgXF3PeGcvACMyMWsuSv7aPXHfliswAbkWuzcwA4TW01ECIGWa
|
||||
cgsDvVFxmfM5NPSuT/UDTa6R5BFISB5ea0N0AR3I
|
||||
MIIEpQIBAAKCAQEAvSQq3d8AeZMTvtqZ13jWCckikyXJSACvkGCQUCJqOceESbg6
|
||||
IHdRzQdoccE4P3sbvNsf9BlbdJKM+neCxabqKaU1PPje4P0tHT57t6yJrMuUh9Nx
|
||||
Ez3Bgh1srNHVS7saKvwHmcKm79jc+wxlioPmEQvQagjny7oTkyLt0sn4LGxBjrcv
|
||||
2JoHOC9f1pxX7l47MaiN0/ctRau7Nr3PFn+pkB4Yf6Z0VyicVJbaUSz39Qo4HQWl
|
||||
1L2hiBP3CS1oKs2Yk0O1aOCMExWrhZQan+ZgHqL1rhgmkPpw2/zwwPt5Vf9CSakv
|
||||
Hwg198EXuTTXtkzYduuIJAm8yp969iEIiG2xTwIDAQABAoIBAGPIw/C/qJF7HYyv
|
||||
6T+7GTiaa2o0IiehbP3/Y8NTFLWc49a8obXlHTvMr7Zr2I/tE+ojtIzkH9K1SjkN
|
||||
eelqsNj9tsOPDI6oIvftsflpxkxqLtclnt8m0oMhoObf4OaONDT/N8dP4SBiSdsM
|
||||
ZDmacnMFx5NZVWiup4sVf2CYexx7qks9FhyN2K5PArCQ4S9LHjFhSJVH4DSEpv7E
|
||||
Ykbp30rhpqV7wSwjgUsm8ZYvI2NOlmffzLSiPdt3vy2K5Q25S/MVEAicg83rfDgK
|
||||
6EluHjeygRI1xU6DJ0hU7tnU7zE9KURoHPUycO3BKzZnzUH26AA36I58Pu4fXWw/
|
||||
Cgmbv2ECgYEA+og9E4ziKCEi3p8gqjIfwTRgWZxDLjEzooB/K0UhEearn/xiX29A
|
||||
FiSzEHKfCB4uSrw5OENg2ckDs8uy08Qmxx7xFXL7AtufAl5fIYaWa0sNSqCaIk7p
|
||||
ebbUmPcaYhKiLzIEd1EYEL38sXVZ62wvSVMRSWvEMq44g1qnoRlDa/8CgYEAwUTt
|
||||
talYNwVmR9ZdkVEWm9ZxirdzoM6NaM6u4Tf34ygptpapdmIFSUhfq4iOiEnRGNg/
|
||||
tuNqhNCIb3LNpJbhRPEzqN7E7qiF/mp7AcJgbuxLZBm12QuLuJdG3nrisKPFXcY1
|
||||
lA4A7CFmNgH3E4THFfgwzyDXsBOxVLXleTqn+rECgYEA9up1P6J3dtOJuV2d5P/3
|
||||
ugRz/X173LfTSxJXw36jZDAy8D/feG19/RT4gnplcKvGNhQiVOhbOOnbw0U8n2fQ
|
||||
TCmbs+cZqyxnH/+AxNsPvvk+RVHZ93xMsY/XIldP4l65B8jFDA+Zp06IESI2mEeM
|
||||
pzi+bd1Phh+dRSCA2865W2MCgYEAlxYsgmQ1WyX0dFpHYU+zzfXRYzDQyrhOYc2Z
|
||||
duVK+yCto1iad7pfCY/zgmRJkI+sT7DV9kJIRjXDQuTLkEyHJF8vFGe6KhxCS8aw
|
||||
DIsI2g4NTd6vg1J8UryoIUqNpqsQoqNNxUVBQVdG0ReuMGsPO8R/W50AIFz0txVP
|
||||
o/rP0LECgYEA7e/mOwCnR+ovmS/CAksmos3oIqvkRkXNKpKe513FVmp3TpTU38ex
|
||||
cBkFNU3hEO31FyrX1hGIKp3N5mHYSQ1lyODHM6teHW0OLWWTwIe8rIGvR2jfRLe0
|
||||
bbkdj40atYVkfeFmpz9uHHG24CUYxJdPc360jbXTVp4i3q8zqgL5aMY=
|
||||
-----END RSA PRIVATE KEY-----
|
||||
|
||||
19
test/fixtures/agent2.cnf
vendored
19
test/fixtures/agent2.cnf
vendored
@ -1,19 +0,0 @@
|
||||
[ req ]
|
||||
default_bits = 1024
|
||||
days = 999
|
||||
distinguished_name = req_distinguished_name
|
||||
attributes = req_attributes
|
||||
prompt = no
|
||||
|
||||
[ req_distinguished_name ]
|
||||
C = US
|
||||
ST = CA
|
||||
L = SF
|
||||
O = Joyent
|
||||
OU = Node.js
|
||||
CN = agent2
|
||||
emailAddress = ry@tinyclouds.org
|
||||
|
||||
[ req_attributes ]
|
||||
challengePassword = A challenge password
|
||||
|
||||
405
test/helpers.js
405
test/helpers.js
@ -1,405 +0,0 @@
|
||||
/*
|
||||
* helpers.js: Helpers for node-http-proxy tests.
|
||||
*
|
||||
* (C) 2010, Charlie Robbins
|
||||
*
|
||||
*/
|
||||
|
||||
var assert = require('assert'),
|
||||
fs = require('fs'),
|
||||
http = require('http'),
|
||||
https = require('https'),
|
||||
path = require('path'),
|
||||
argv = require('optimist').argv,
|
||||
request = require('request'),
|
||||
vows = require('vows'),
|
||||
websocket = require('../vendor/websocket'),
|
||||
httpProxy = require('../lib/node-http-proxy');
|
||||
|
||||
var loadHttps = exports.loadHttps = function () {
|
||||
return {
|
||||
key: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-key.pem'), 'utf8'),
|
||||
cert: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-cert.pem'), 'utf8')
|
||||
};
|
||||
};
|
||||
|
||||
var parseProtocol = exports.parseProtocol = function () {
|
||||
function setupProtocol (secure) {
|
||||
return {
|
||||
secure: secure,
|
||||
protocols: {
|
||||
http: secure ? 'https' : 'http',
|
||||
ws: secure ? 'wss' : 'ws'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
source: setupProtocol(argv.source === 'secure'),
|
||||
target: setupProtocol(argv.target === 'secure')
|
||||
};
|
||||
}
|
||||
|
||||
var TestRunner = exports.TestRunner = function (options) {
|
||||
options = options || {};
|
||||
this.source = options.source || {};
|
||||
this.target = options.target || {};
|
||||
this.testServers = [];
|
||||
|
||||
if (this.source.secure) {
|
||||
this.source.https = loadHttps();
|
||||
}
|
||||
|
||||
if (this.target.secure) {
|
||||
this.target.https = loadHttps();
|
||||
}
|
||||
};
|
||||
|
||||
TestRunner.prototype.assertProxied = function (host, proxyPort, port, createProxy) {
|
||||
var self = this,
|
||||
assertion = "should receive 'hello " + host + "'",
|
||||
output = 'hello ' + host;
|
||||
|
||||
var test = {
|
||||
topic: function () {
|
||||
var that = this,
|
||||
options;
|
||||
|
||||
options = {
|
||||
method: 'GET',
|
||||
uri: self.source.protocols.http + '://localhost:' + proxyPort,
|
||||
headers: {
|
||||
host: host
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
function startTest () {
|
||||
if (port) {
|
||||
return self.startTargetServer(port, output, function () {
|
||||
request(options, that.callback);
|
||||
});
|
||||
}
|
||||
|
||||
request(options, this.callback);
|
||||
}
|
||||
|
||||
return createProxy ? createProxy(startTest) : startTest();
|
||||
}
|
||||
};
|
||||
|
||||
test[assertion] = function (err, res, body) {
|
||||
assert.isNull(err);
|
||||
assert.equal(body, output);
|
||||
};
|
||||
|
||||
return test;
|
||||
};
|
||||
|
||||
TestRunner.prototype.assertResponseCode = function (proxyPort, statusCode, createProxy) {
|
||||
var assertion = "should receive " + statusCode + " responseCode",
|
||||
protocol = this.source.protocols.http;
|
||||
|
||||
var test = {
|
||||
topic: function () {
|
||||
var that = this, options = {
|
||||
method: 'GET',
|
||||
uri: protocol + '://localhost:' + proxyPort,
|
||||
headers: {
|
||||
host: 'unknown.com'
|
||||
}
|
||||
};
|
||||
|
||||
if (createProxy) {
|
||||
return createProxy(function () {
|
||||
request(options, that.callback);
|
||||
});
|
||||
}
|
||||
|
||||
request(options, this.callback);
|
||||
}
|
||||
};
|
||||
|
||||
test[assertion] = function (err, res, body) {
|
||||
assert.isNull(err);
|
||||
assert.equal(res.statusCode, statusCode);
|
||||
};
|
||||
|
||||
return test;
|
||||
};
|
||||
|
||||
// A test helper to check and see if the http headers were set properly.
|
||||
TestRunner.prototype.assertHeaders = function (proxyPort, headerName, createProxy) {
|
||||
var assertion = "should receive http header \"" + headerName + "\"",
|
||||
protocol = this.source.protocols.http;
|
||||
|
||||
var test = {
|
||||
topic: function () {
|
||||
var that = this, options = {
|
||||
method: 'GET',
|
||||
uri: protocol + '://localhost:' + proxyPort,
|
||||
headers: {
|
||||
host: 'unknown.com'
|
||||
}
|
||||
};
|
||||
|
||||
if (createProxy) {
|
||||
return createProxy(function () {
|
||||
request(options, that.callback);
|
||||
});
|
||||
}
|
||||
|
||||
request(options, this.callback);
|
||||
}
|
||||
};
|
||||
|
||||
test[assertion] = function (err, res, body) {
|
||||
assert.isNull(err);
|
||||
assert.isNotNull(res.headers[headerName]);
|
||||
};
|
||||
|
||||
return test;
|
||||
};
|
||||
|
||||
|
||||
//
|
||||
// WebSocketTest
|
||||
//
|
||||
TestRunner.prototype.webSocketTest = function (options) {
|
||||
var self = this;
|
||||
|
||||
this.startTargetServer(options.ports.target, 'hello websocket', function (err, target) {
|
||||
var socket = options.io.listen(target);
|
||||
|
||||
if (options.onListen) {
|
||||
options.onListen(socket);
|
||||
}
|
||||
|
||||
self.startProxyServer(
|
||||
options.ports.proxy,
|
||||
options.ports.target,
|
||||
options.host,
|
||||
function (err, proxy) {
|
||||
if (options.onServer) { options.onServer(proxy) }
|
||||
|
||||
//
|
||||
// Setup the web socket against our proxy
|
||||
//
|
||||
var uri = options.wsprotocol + '://' + options.host + ':' + options.ports.proxy;
|
||||
var ws = new websocket.WebSocket(uri + '/socket.io/websocket/', 'borf', {
|
||||
origin: options.protocol + '://' + options.host
|
||||
});
|
||||
|
||||
if (options.onWsupgrade) { ws.on('wsupgrade', options.onWsupgrade) }
|
||||
if (options.onMessage) { ws.on('message', options.onMessage) }
|
||||
if (options.onOpen) { ws.on('open', function () { options.onOpen(ws) }) }
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// WebSocketTestWithTable
|
||||
//
|
||||
TestRunner.prototype.webSocketTestWithTable = function (options) {
|
||||
var self = this;
|
||||
|
||||
this.startTargetServer(options.ports.target, 'hello websocket', function (err, target) {
|
||||
var socket = options.io.listen(target);
|
||||
|
||||
if (options.onListen) {
|
||||
options.onListen(socket);
|
||||
}
|
||||
|
||||
self.startProxyServerWithTable(
|
||||
options.ports.proxy,
|
||||
{ router: options.router },
|
||||
function (err, proxy) {
|
||||
if (options.onServer) { options.onServer(proxy) }
|
||||
|
||||
//
|
||||
// Setup the web socket against our proxy
|
||||
//
|
||||
var uri = options.wsprotocol + '://' + options.host + ':' + options.ports.proxy;
|
||||
var ws = new websocket.WebSocket(uri + '/socket.io/websocket/', 'borf', {
|
||||
origin: options.protocol + '://' + options.host
|
||||
});
|
||||
|
||||
if (options.onWsupgrade) { ws.on('wsupgrade', options.onWsupgrade) }
|
||||
if (options.onMessage) { ws.on('message', options.onMessage) }
|
||||
if (options.onOpen) { ws.on('open', function () { options.onOpen(ws) }) }
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Creates the reverse proxy server
|
||||
//
|
||||
TestRunner.prototype.startProxyServer = function (port, targetPort, host, callback) {
|
||||
var that = this,
|
||||
proxyServer = httpProxy.createServer(host, targetPort, this.getOptions());
|
||||
|
||||
proxyServer.listen(port, function () {
|
||||
that.testServers.push(proxyServer);
|
||||
callback(null, proxyServer);
|
||||
});
|
||||
};
|
||||
|
||||
//
|
||||
// Creates the reverse proxy server with a specified latency
|
||||
//
|
||||
TestRunner.prototype.startLatentProxyServer = function (port, targetPort, host, latency, callback) {
|
||||
//
|
||||
// Initialize the nodeProxy and start proxying the request
|
||||
//
|
||||
var that = this,
|
||||
proxyServer;
|
||||
|
||||
proxyServer = httpProxy.createServer(host, targetPort, function (req, res, proxy) {
|
||||
var buffer = httpProxy.buffer(req);
|
||||
|
||||
setTimeout(function () {
|
||||
proxy.proxyRequest(req, res, buffer);
|
||||
}, latency);
|
||||
}, this.getOptions());
|
||||
|
||||
proxyServer.listen(port, function () {
|
||||
that.testServers.push(proxyServer);
|
||||
callback();
|
||||
});
|
||||
};
|
||||
|
||||
//
|
||||
// Creates the reverse proxy server with a ProxyTable
|
||||
//
|
||||
TestRunner.prototype.startProxyServerWithTable = function (port, options, callback) {
|
||||
var that = this,
|
||||
proxyServer = httpProxy.createServer(merge({}, options, this.getOptions()));
|
||||
|
||||
proxyServer.listen(port, function () {
|
||||
that.testServers.push(proxyServer);
|
||||
callback();
|
||||
});
|
||||
|
||||
return proxyServer;
|
||||
};
|
||||
|
||||
//
|
||||
// Creates a latent reverse proxy server using a ProxyTable
|
||||
//
|
||||
TestRunner.prototype.startProxyServerWithTableAndLatency = function (port, latency, options, callback) {
|
||||
//
|
||||
// Initialize the nodeProxy and start proxying the request
|
||||
//
|
||||
var that = this,
|
||||
proxy = new httpProxy.RoutingProxy(merge({}, options, this.getOptions())),
|
||||
proxyServer;
|
||||
|
||||
var handler = function (req, res) {
|
||||
var buffer = httpProxy.buffer(req);
|
||||
setTimeout(function () {
|
||||
proxy.proxyRequest(req, res, {
|
||||
buffer: buffer
|
||||
});
|
||||
}, latency);
|
||||
};
|
||||
|
||||
proxyServer = this.source.https
|
||||
? https.createServer(this.source.https, handler)
|
||||
: http.createServer(handler);
|
||||
|
||||
proxyServer.listen(port, function () {
|
||||
that.testServers.push(proxyServer);
|
||||
callback();
|
||||
});
|
||||
|
||||
return proxyServer;
|
||||
};
|
||||
|
||||
//
|
||||
// Creates proxy server forwarding to the specified options
|
||||
//
|
||||
TestRunner.prototype.startProxyServerWithForwarding = function (port, targetPort, host, options, callback) {
|
||||
var that = this,
|
||||
proxyServer = httpProxy.createServer(targetPort, host, merge({}, options, this.getOptions()));
|
||||
|
||||
proxyServer.listen(port, function () {
|
||||
that.testServers.push(proxyServer);
|
||||
callback(null, proxyServer);
|
||||
});
|
||||
};
|
||||
|
||||
//
|
||||
// Creates the 'hellonode' server
|
||||
//
|
||||
TestRunner.prototype.startTargetServer = function (port, output, callback) {
|
||||
var that = this,
|
||||
targetServer,
|
||||
handler;
|
||||
|
||||
handler = function (req, res) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write(output);
|
||||
res.end();
|
||||
};
|
||||
|
||||
targetServer = this.target.https
|
||||
? https.createServer(this.target.https, handler)
|
||||
: http.createServer(handler);
|
||||
|
||||
targetServer.listen(port, function () {
|
||||
that.testServers.push(targetServer);
|
||||
callback(null, targetServer);
|
||||
});
|
||||
};
|
||||
|
||||
//
|
||||
// Close all of the testServers
|
||||
//
|
||||
TestRunner.prototype.closeServers = function () {
|
||||
this.testServers.forEach(function (server) {
|
||||
server.close();
|
||||
});
|
||||
|
||||
return this.testServers;
|
||||
};
|
||||
|
||||
//
|
||||
// Creates a new instance of the options to
|
||||
// pass to `httpProxy.createServer()`
|
||||
//
|
||||
TestRunner.prototype.getOptions = function () {
|
||||
return {
|
||||
https: clone(this.source.https),
|
||||
target: {
|
||||
https: clone(this.target.https)
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
//
|
||||
// ### @private function clone (object)
|
||||
// #### @object {Object} Object to clone
|
||||
// Shallow clones the specified object.
|
||||
//
|
||||
function clone (object) {
|
||||
if (!object) { return null }
|
||||
|
||||
return Object.keys(object).reduce(function (obj, k) {
|
||||
obj[k] = object[k];
|
||||
return obj;
|
||||
}, {});
|
||||
}
|
||||
|
||||
function merge (target) {
|
||||
var objs = Array.prototype.slice.call(arguments, 1);
|
||||
objs.forEach(function(o) {
|
||||
Object.keys(o).forEach(function (attr) {
|
||||
if (! o.__lookupGetter__(attr)) {
|
||||
target[attr] = o[attr];
|
||||
}
|
||||
});
|
||||
});
|
||||
return target;
|
||||
}
|
||||
@ -1,95 +0,0 @@
|
||||
/*
|
||||
node-http-proxy-test.js: http proxy for node.js
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Marak Squires and Fedor Indutny
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
var assert = require('assert'),
|
||||
util = require('util'),
|
||||
request = require('request'),
|
||||
vows = require('vows'),
|
||||
helpers = require('../helpers');
|
||||
|
||||
var forwardOptions = {
|
||||
forward: {
|
||||
port: 8300,
|
||||
host: 'localhost'
|
||||
}
|
||||
};
|
||||
|
||||
var badForwardOptions = {
|
||||
forward: {
|
||||
port: 9000,
|
||||
host: 'localhost'
|
||||
}
|
||||
};
|
||||
|
||||
var options = helpers.parseProtocol(),
|
||||
testName = [options.source.protocols.http, options.target.protocols.http].join('-to-'),
|
||||
runner = new helpers.TestRunner(options);
|
||||
|
||||
vows.describe('node-http-proxy/http-proxy/' + testName).addBatch({
|
||||
"When using server created by httpProxy.createServer()": {
|
||||
"with no latency" : {
|
||||
"and a valid target server": runner.assertProxied('localhost', 8080, 8081, function (callback) {
|
||||
runner.startProxyServer(8080, 8081, 'localhost', callback);
|
||||
}),
|
||||
"and without a valid target server": runner.assertResponseCode(8082, 500, function (callback) {
|
||||
runner.startProxyServer(8082, 9000, 'localhost', callback);
|
||||
})
|
||||
},
|
||||
"with latency": {
|
||||
"and a valid target server": runner.assertProxied('localhost', 8083, 8084, function (callback) {
|
||||
runner.startLatentProxyServer(8083, 8084, 'localhost', 1000, callback);
|
||||
}),
|
||||
"and without a valid target server": runner.assertResponseCode(8085, 500, function (callback) {
|
||||
runner.startLatentProxyServer(8085, 9000, 'localhost', 1000, callback);
|
||||
})
|
||||
},
|
||||
"with forwarding enabled": {
|
||||
topic: function () {
|
||||
runner.startTargetServer(8300, 'forward proxy', this.callback);
|
||||
},
|
||||
"with no latency" : {
|
||||
"and a valid target server": runner.assertProxied('localhost', 8120, 8121, function (callback) {
|
||||
runner.startProxyServerWithForwarding(8120, 8121, 'localhost', forwardOptions, callback);
|
||||
}),
|
||||
"and also a valid target server": runner.assertHeaders(8122, "x-forwarded-for", function (callback) {
|
||||
runner.startProxyServerWithForwarding(8122, 8123, 'localhost', forwardOptions, callback);
|
||||
}),
|
||||
"and without a valid forward server": runner.assertProxied('localhost', 8124, 8125, function (callback) {
|
||||
runner.startProxyServerWithForwarding(8124, 8125, 'localhost', badForwardOptions, callback);
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
"When the tests are over": {
|
||||
topic: function () {
|
||||
return runner.closeServers();
|
||||
},
|
||||
"the servers should clean up": function () {
|
||||
assert.isTrue(true);
|
||||
}
|
||||
}
|
||||
}).export(module);
|
||||
@ -1,127 +0,0 @@
|
||||
/*
|
||||
* proxy-table-test.js: Tests for the ProxyTable object.
|
||||
*
|
||||
* (C) 2010, Charlie Robbins
|
||||
*
|
||||
*/
|
||||
|
||||
var assert = require('assert'),
|
||||
fs = require('fs'),
|
||||
path = require('path'),
|
||||
util = require('util'),
|
||||
argv = require('optimist').argv,
|
||||
request = require('request'),
|
||||
vows = require('vows'),
|
||||
helpers = require('../helpers');
|
||||
|
||||
var options = helpers.parseProtocol(),
|
||||
testName = [options.source.protocols.http, options.target.protocols.http].join('-to-'),
|
||||
runner = new helpers.TestRunner(options),
|
||||
routeFile = path.join(__dirname, 'config.json');
|
||||
|
||||
var fileOptions = {
|
||||
router: {
|
||||
"foo.com": "127.0.0.1:8101",
|
||||
"bar.com": "127.0.0.1:8102"
|
||||
}
|
||||
};
|
||||
|
||||
var defaultOptions = {
|
||||
router: {
|
||||
"foo.com": "127.0.0.1:8091",
|
||||
"bar.com": "127.0.0.1:8092"
|
||||
}
|
||||
};
|
||||
|
||||
var hostnameOptions = {
|
||||
hostnameOnly: true,
|
||||
router: {
|
||||
"foo.com": "127.0.0.1:8091",
|
||||
"bar.com": "127.0.0.1:8092"
|
||||
}
|
||||
};
|
||||
|
||||
vows.describe('node-http-proxy/routing-proxy/' + testName).addBatch({
|
||||
"When using server created by httpProxy.createServer()": {
|
||||
"when passed a routing table": {
|
||||
"and routing by RegExp": {
|
||||
topic: function () {
|
||||
this.server = runner.startProxyServerWithTable(8090, defaultOptions, this.callback);
|
||||
},
|
||||
"an incoming request to foo.com": runner.assertProxied('foo.com', 8090, 8091),
|
||||
"an incoming request to bar.com": runner.assertProxied('bar.com', 8090, 8092),
|
||||
"an incoming request to unknown.com": runner.assertResponseCode(8090, 404)
|
||||
},
|
||||
"and routing by Hostname": {
|
||||
topic: function () {
|
||||
this.server = runner.startProxyServerWithTable(8093, hostnameOptions, this.callback);
|
||||
},
|
||||
"an incoming request to foo.com": runner.assertProxied('foo.com', 8093, 8094),
|
||||
"an incoming request to bar.com": runner.assertProxied('bar.com', 8093, 8095),
|
||||
"an incoming request to unknown.com": runner.assertResponseCode(8093, 404)
|
||||
}
|
||||
},
|
||||
"when passed a routing file": {
|
||||
topic: function () {
|
||||
fs.writeFileSync(routeFile, JSON.stringify(fileOptions));
|
||||
this.server = runner.startProxyServerWithTable(8100, {
|
||||
router: routeFile
|
||||
}, this.callback);
|
||||
},
|
||||
"an incoming request to foo.com": runner.assertProxied('foo.com', 8100, 8101),
|
||||
"an incoming request to bar.com": runner.assertProxied('bar.com', 8100, 8102),
|
||||
"an incoming request to unknown.com": runner.assertResponseCode(8100, 404),
|
||||
"an incoming request to dynamic.com": {
|
||||
"after the file has been modified": {
|
||||
topic: function () {
|
||||
var that = this,
|
||||
data = fs.readFileSync(routeFile),
|
||||
config = JSON.parse(data);
|
||||
|
||||
config.router['dynamic.com'] = "127.0.0.1:8103";
|
||||
fs.writeFileSync(routeFile, JSON.stringify(config));
|
||||
|
||||
this.server.on('routes', function () {
|
||||
runner.startTargetServer(8103, 'hello dynamic.com', function () {
|
||||
request({
|
||||
method: 'GET',
|
||||
uri: options.source.protocols.http + '://localhost:8100',
|
||||
headers: {
|
||||
host: 'dynamic.com'
|
||||
}
|
||||
}, that.callback);
|
||||
});
|
||||
});
|
||||
},
|
||||
"should receive 'hello dynamic.com'": function (err, res, body) {
|
||||
assert.equal(body, 'hello dynamic.com');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
"When using an instance of ProxyTable combined with HttpProxy directly": {
|
||||
topic: function () {
|
||||
this.server = runner.startProxyServerWithTableAndLatency(8110, 100, {
|
||||
router: {
|
||||
'foo.com': 'localhost:8111',
|
||||
'bar.com': 'localhost:8112'
|
||||
}
|
||||
}, this.callback);
|
||||
},
|
||||
"an incoming request to foo.com": runner.assertProxied('foo.com', 8110, 8111),
|
||||
"an incoming request to bar.com": runner.assertProxied('bar.com', 8110, 8112),
|
||||
"an incoming request to unknown.com": runner.assertResponseCode(8110, 404)
|
||||
}
|
||||
}).addBatch({
|
||||
"When the tests are over": {
|
||||
topic: function () {
|
||||
//fs.unlinkSync(routeFile);
|
||||
return runner.closeServers();
|
||||
},
|
||||
"the servers should clean up": function () {
|
||||
assert.isTrue(true);
|
||||
}
|
||||
}
|
||||
}).export(module);
|
||||
397
test/lib-http-proxy-common-test.js
Normal file
397
test/lib-http-proxy-common-test.js
Normal file
@ -0,0 +1,397 @@
|
||||
var common = require('../lib/http-proxy/common'),
|
||||
url = require('url'),
|
||||
expect = require('expect.js');
|
||||
|
||||
describe('lib/http-proxy/common.js', function () {
|
||||
describe('#setupOutgoing', function () {
|
||||
it('should setup the correct headers', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing,
|
||||
{
|
||||
agent : '?',
|
||||
target: {
|
||||
host : 'hey',
|
||||
hostname : 'how',
|
||||
socketPath: 'are',
|
||||
port : 'you',
|
||||
},
|
||||
headers: {'fizz': 'bang', 'overwritten':true},
|
||||
localAddress: 'local.address',
|
||||
auth:'username:pass'
|
||||
},
|
||||
{
|
||||
method : 'i',
|
||||
url : 'am',
|
||||
headers : {'pro':'xy','overwritten':false}
|
||||
});
|
||||
|
||||
expect(outgoing.host).to.eql('hey');
|
||||
expect(outgoing.hostname).to.eql('how');
|
||||
expect(outgoing.socketPath).to.eql('are');
|
||||
expect(outgoing.port).to.eql('you');
|
||||
expect(outgoing.agent).to.eql('?');
|
||||
|
||||
expect(outgoing.method).to.eql('i');
|
||||
expect(outgoing.path).to.eql('am');
|
||||
|
||||
expect(outgoing.headers.pro).to.eql('xy');
|
||||
expect(outgoing.headers.fizz).to.eql('bang');
|
||||
expect(outgoing.headers.overwritten).to.eql(true);
|
||||
expect(outgoing.localAddress).to.eql('local.address');
|
||||
expect(outgoing.auth).to.eql('username:pass');
|
||||
});
|
||||
|
||||
it('should not override agentless upgrade header', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing,
|
||||
{
|
||||
agent: undefined,
|
||||
target: {
|
||||
host : 'hey',
|
||||
hostname : 'how',
|
||||
socketPath: 'are',
|
||||
port : 'you',
|
||||
},
|
||||
headers: {'connection': 'upgrade'},
|
||||
},
|
||||
{
|
||||
method : 'i',
|
||||
url : 'am',
|
||||
headers : {'pro':'xy','overwritten':false}
|
||||
});
|
||||
expect(outgoing.headers.connection).to.eql('upgrade');
|
||||
});
|
||||
|
||||
it('should not override agentless connection: contains upgrade', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing,
|
||||
{
|
||||
agent: undefined,
|
||||
target: {
|
||||
host : 'hey',
|
||||
hostname : 'how',
|
||||
socketPath: 'are',
|
||||
port : 'you',
|
||||
},
|
||||
headers: {'connection': 'keep-alive, upgrade'}, // this is what Firefox sets
|
||||
},
|
||||
{
|
||||
method : 'i',
|
||||
url : 'am',
|
||||
headers : {'pro':'xy','overwritten':false}
|
||||
});
|
||||
expect(outgoing.headers.connection).to.eql('keep-alive, upgrade');
|
||||
});
|
||||
|
||||
it('should override agentless connection: contains improper upgrade', function () {
|
||||
// sanity check on upgrade regex
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing,
|
||||
{
|
||||
agent: undefined,
|
||||
target: {
|
||||
host : 'hey',
|
||||
hostname : 'how',
|
||||
socketPath: 'are',
|
||||
port : 'you',
|
||||
},
|
||||
headers: {'connection': 'keep-alive, not upgrade'},
|
||||
},
|
||||
{
|
||||
method : 'i',
|
||||
url : 'am',
|
||||
headers : {'pro':'xy','overwritten':false}
|
||||
});
|
||||
expect(outgoing.headers.connection).to.eql('close');
|
||||
});
|
||||
|
||||
it('should override agentless non-upgrade header to close', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing,
|
||||
{
|
||||
agent: undefined,
|
||||
target: {
|
||||
host : 'hey',
|
||||
hostname : 'how',
|
||||
socketPath: 'are',
|
||||
port : 'you',
|
||||
},
|
||||
headers: {'connection': 'xyz'},
|
||||
},
|
||||
{
|
||||
method : 'i',
|
||||
url : 'am',
|
||||
headers : {'pro':'xy','overwritten':false}
|
||||
});
|
||||
expect(outgoing.headers.connection).to.eql('close');
|
||||
});
|
||||
|
||||
it('should set the agent to false if none is given', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing, {target:
|
||||
'http://localhost'
|
||||
}, { url: '/' });
|
||||
expect(outgoing.agent).to.eql(false);
|
||||
});
|
||||
|
||||
it('set the port according to the protocol', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing,
|
||||
{
|
||||
agent : '?',
|
||||
target: {
|
||||
host : 'how',
|
||||
hostname : 'are',
|
||||
socketPath: 'you',
|
||||
protocol: 'https:'
|
||||
}
|
||||
},
|
||||
{
|
||||
method : 'i',
|
||||
url : 'am',
|
||||
headers : {pro:'xy'}
|
||||
});
|
||||
|
||||
expect(outgoing.host).to.eql('how');
|
||||
expect(outgoing.hostname).to.eql('are');
|
||||
expect(outgoing.socketPath).to.eql('you');
|
||||
expect(outgoing.agent).to.eql('?');
|
||||
|
||||
expect(outgoing.method).to.eql('i');
|
||||
expect(outgoing.path).to.eql('am');
|
||||
expect(outgoing.headers.pro).to.eql('xy');
|
||||
|
||||
expect(outgoing.port).to.eql(443);
|
||||
});
|
||||
|
||||
it('should keep the original target path in the outgoing path', function(){
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing, {target:
|
||||
{ path: 'some-path' }
|
||||
}, { url : 'am' });
|
||||
|
||||
expect(outgoing.path).to.eql('some-path/am');
|
||||
});
|
||||
|
||||
it('should keep the original forward path in the outgoing path', function(){
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: {},
|
||||
forward: {
|
||||
path: 'some-path'
|
||||
}
|
||||
}, {
|
||||
url : 'am'
|
||||
}, 'forward');
|
||||
|
||||
expect(outgoing.path).to.eql('some-path/am');
|
||||
});
|
||||
|
||||
it('should properly detect https/wss protocol without the colon', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: {
|
||||
protocol: 'https',
|
||||
host: 'whatever.com'
|
||||
}
|
||||
}, { url: '/' });
|
||||
|
||||
expect(outgoing.port).to.eql(443);
|
||||
});
|
||||
|
||||
it('should not prepend the target path to the outgoing path with prependPath = false', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: { path: 'hellothere' },
|
||||
prependPath: false
|
||||
}, { url: 'hi' });
|
||||
|
||||
expect(outgoing.path).to.eql('hi');
|
||||
})
|
||||
|
||||
it('should properly join paths', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: { path: '/forward' },
|
||||
}, { url: '/static/path' });
|
||||
|
||||
expect(outgoing.path).to.eql('/forward/static/path');
|
||||
})
|
||||
|
||||
it('should not modify the query string', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: { path: '/forward' },
|
||||
}, { url: '/?foo=bar//&target=http://foobar.com/?a=1%26b=2&other=2' });
|
||||
|
||||
expect(outgoing.path).to.eql('/forward/?foo=bar//&target=http://foobar.com/?a=1%26b=2&other=2');
|
||||
})
|
||||
|
||||
//
|
||||
// This is the proper failing test case for the common.join problem
|
||||
//
|
||||
it('should correctly format the toProxy URL', function () {
|
||||
var outgoing = {};
|
||||
var google = 'https://google.com'
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: url.parse('http://sometarget.com:80'),
|
||||
toProxy: true,
|
||||
}, { url: google });
|
||||
|
||||
expect(outgoing.path).to.eql('/' + google);
|
||||
});
|
||||
|
||||
it('should not replace :\ to :\\ when no https word before', function () {
|
||||
var outgoing = {};
|
||||
var google = 'https://google.com:/join/join.js'
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: url.parse('http://sometarget.com:80'),
|
||||
toProxy: true,
|
||||
}, { url: google });
|
||||
|
||||
expect(outgoing.path).to.eql('/' + google);
|
||||
});
|
||||
|
||||
it('should not replace :\ to :\\ when no http word before', function () {
|
||||
var outgoing = {};
|
||||
var google = 'http://google.com:/join/join.js'
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: url.parse('http://sometarget.com:80'),
|
||||
toProxy: true,
|
||||
}, { url: google });
|
||||
|
||||
expect(outgoing.path).to.eql('/' + google);
|
||||
});
|
||||
|
||||
describe('when using ignorePath', function () {
|
||||
it('should ignore the path of the `req.url` passed in but use the target path', function () {
|
||||
var outgoing = {};
|
||||
var myEndpoint = 'https://whatever.com/some/crazy/path/whoooo';
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: url.parse(myEndpoint),
|
||||
ignorePath: true
|
||||
}, { url: '/more/crazy/pathness' });
|
||||
|
||||
expect(outgoing.path).to.eql('/some/crazy/path/whoooo');
|
||||
});
|
||||
|
||||
it('and prependPath: false, it should ignore path of target and incoming request', function () {
|
||||
var outgoing = {};
|
||||
var myEndpoint = 'https://whatever.com/some/crazy/path/whoooo';
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: url.parse(myEndpoint),
|
||||
ignorePath: true,
|
||||
prependPath: false
|
||||
}, { url: '/more/crazy/pathness' });
|
||||
|
||||
expect(outgoing.path).to.eql('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('when using changeOrigin', function () {
|
||||
it('should correctly set the port to the host when it is a non-standard port using url.parse', function () {
|
||||
var outgoing = {};
|
||||
var myEndpoint = 'https://myCouch.com:6984';
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: url.parse(myEndpoint),
|
||||
changeOrigin: true
|
||||
}, { url: '/' });
|
||||
|
||||
expect(outgoing.headers.host).to.eql('mycouch.com:6984');
|
||||
});
|
||||
|
||||
it('should correctly set the port to the host when it is a non-standard port when setting host and port manually (which ignores port)', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: {
|
||||
protocol: 'https:',
|
||||
host: 'mycouch.com',
|
||||
port: 6984
|
||||
},
|
||||
changeOrigin: true
|
||||
}, { url: '/' });
|
||||
expect(outgoing.headers.host).to.eql('mycouch.com:6984');
|
||||
})
|
||||
});
|
||||
|
||||
it('should pass through https client parameters', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing,
|
||||
{
|
||||
agent : '?',
|
||||
target: {
|
||||
host : 'how',
|
||||
hostname : 'are',
|
||||
socketPath: 'you',
|
||||
protocol: 'https:',
|
||||
pfx: 'my-pfx',
|
||||
key: 'my-key',
|
||||
passphrase: 'my-passphrase',
|
||||
cert: 'my-cert',
|
||||
ca: 'my-ca',
|
||||
ciphers: 'my-ciphers',
|
||||
secureProtocol: 'my-secure-protocol'
|
||||
}
|
||||
},
|
||||
{
|
||||
method : 'i',
|
||||
url : 'am'
|
||||
});
|
||||
|
||||
expect(outgoing.pfx).eql('my-pfx');
|
||||
expect(outgoing.key).eql('my-key');
|
||||
expect(outgoing.passphrase).eql('my-passphrase');
|
||||
expect(outgoing.cert).eql('my-cert');
|
||||
expect(outgoing.ca).eql('my-ca');
|
||||
expect(outgoing.ciphers).eql('my-ciphers');
|
||||
expect(outgoing.secureProtocol).eql('my-secure-protocol');
|
||||
});
|
||||
|
||||
it('should handle overriding the `method` of the http request', function () {
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing, {
|
||||
target: url.parse('https://whooooo.com'),
|
||||
method: 'POST' ,
|
||||
}, { method: 'GET', url: '' });
|
||||
|
||||
expect(outgoing.method).eql('POST');
|
||||
});
|
||||
|
||||
// url.parse('').path => null
|
||||
it('should not pass null as last arg to #urlJoin', function(){
|
||||
var outgoing = {};
|
||||
common.setupOutgoing(outgoing, {target:
|
||||
{ path: '' }
|
||||
}, { url : '' });
|
||||
|
||||
expect(outgoing.path).to.be('');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('#setupSocket', function () {
|
||||
it('should setup a socket', function () {
|
||||
var socketConfig = {
|
||||
timeout: null,
|
||||
nodelay: false,
|
||||
keepalive: false
|
||||
},
|
||||
stubSocket = {
|
||||
setTimeout: function (num) {
|
||||
socketConfig.timeout = num;
|
||||
},
|
||||
setNoDelay: function (bol) {
|
||||
socketConfig.nodelay = bol;
|
||||
},
|
||||
setKeepAlive: function (bol) {
|
||||
socketConfig.keepalive = bol;
|
||||
}
|
||||
}
|
||||
returnValue = common.setupSocket(stubSocket);
|
||||
|
||||
expect(socketConfig.timeout).to.eql(0);
|
||||
expect(socketConfig.nodelay).to.eql(true);
|
||||
expect(socketConfig.keepalive).to.eql(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
536
test/lib-http-proxy-passes-web-incoming-test.js
Normal file
536
test/lib-http-proxy-passes-web-incoming-test.js
Normal file
@ -0,0 +1,536 @@
|
||||
var webPasses = require('../lib/http-proxy/passes/web-incoming'),
|
||||
httpProxy = require('../lib/http-proxy'),
|
||||
expect = require('expect.js'),
|
||||
concat = require('concat-stream'),
|
||||
async = require('async'),
|
||||
url = require('url'),
|
||||
http = require('http');
|
||||
|
||||
describe('lib/http-proxy/passes/web.js', function() {
|
||||
describe('#deleteLength', function() {
|
||||
it('should change `content-length` for DELETE requests', function() {
|
||||
var stubRequest = {
|
||||
method: 'DELETE',
|
||||
headers: {}
|
||||
};
|
||||
webPasses.deleteLength(stubRequest, {}, {});
|
||||
expect(stubRequest.headers['content-length']).to.eql('0');
|
||||
});
|
||||
|
||||
it('should change `content-length` for OPTIONS requests', function() {
|
||||
var stubRequest = {
|
||||
method: 'OPTIONS',
|
||||
headers: {}
|
||||
};
|
||||
webPasses.deleteLength(stubRequest, {}, {});
|
||||
expect(stubRequest.headers['content-length']).to.eql('0');
|
||||
});
|
||||
|
||||
it('should remove `transfer-encoding` from empty DELETE requests', function() {
|
||||
var stubRequest = {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'transfer-encoding': 'chunked'
|
||||
}
|
||||
};
|
||||
webPasses.deleteLength(stubRequest, {}, {});
|
||||
expect(stubRequest.headers['content-length']).to.eql('0');
|
||||
expect(stubRequest.headers).to.not.have.key('transfer-encoding');
|
||||
});
|
||||
});
|
||||
|
||||
describe('#timeout', function() {
|
||||
it('should set timeout on the socket', function() {
|
||||
var done = false, stubRequest = {
|
||||
socket: {
|
||||
setTimeout: function(value) { done = value; }
|
||||
}
|
||||
}
|
||||
|
||||
webPasses.timeout(stubRequest, {}, { timeout: 5000});
|
||||
expect(done).to.eql(5000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#XHeaders', function () {
|
||||
var stubRequest = {
|
||||
connection: {
|
||||
remoteAddress: '192.168.1.2',
|
||||
remotePort: '8080'
|
||||
},
|
||||
headers: {
|
||||
host: '192.168.1.2:8080'
|
||||
}
|
||||
}
|
||||
|
||||
it('set the correct x-forwarded-* headers', function () {
|
||||
webPasses.XHeaders(stubRequest, {}, { xfwd: true });
|
||||
expect(stubRequest.headers['x-forwarded-for']).to.be('192.168.1.2');
|
||||
expect(stubRequest.headers['x-forwarded-port']).to.be('8080');
|
||||
expect(stubRequest.headers['x-forwarded-proto']).to.be('http');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#createProxyServer.web() using own http server', function () {
|
||||
it('should proxy the request using the web proxy handler', function (done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:8080'
|
||||
});
|
||||
|
||||
function requestHandler(req, res) {
|
||||
proxy.web(req, res);
|
||||
}
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
source.close();
|
||||
proxyServer.close();
|
||||
expect(req.method).to.eql('GET');
|
||||
expect(req.headers.host.split(':')[1]).to.eql('8081');
|
||||
done();
|
||||
});
|
||||
|
||||
proxyServer.listen('8081');
|
||||
source.listen('8080');
|
||||
|
||||
http.request('http://127.0.0.1:8081', function() {}).end();
|
||||
});
|
||||
|
||||
it('should detect a proxyReq event and modify headers', function (done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:8080',
|
||||
});
|
||||
|
||||
proxy.on('proxyReq', function(proxyReq, req, res, options) {
|
||||
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
|
||||
});
|
||||
|
||||
function requestHandler(req, res) {
|
||||
proxy.web(req, res);
|
||||
}
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
source.close();
|
||||
proxyServer.close();
|
||||
expect(req.headers['x-special-proxy-header']).to.eql('foobar');
|
||||
done();
|
||||
});
|
||||
|
||||
proxyServer.listen('8081');
|
||||
source.listen('8080');
|
||||
|
||||
http.request('http://127.0.0.1:8081', function() {}).end();
|
||||
});
|
||||
|
||||
it('should skip proxyReq event when handling a request with header "expect: 100-continue" [https://www.npmjs.com/advisories/1486]', function (done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:8080',
|
||||
});
|
||||
|
||||
proxy.on('proxyReq', function(proxyReq, req, res, options) {
|
||||
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
|
||||
});
|
||||
|
||||
function requestHandler(req, res) {
|
||||
proxy.web(req, res);
|
||||
}
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
source.close();
|
||||
proxyServer.close();
|
||||
expect(req.headers['x-special-proxy-header']).to.not.eql('foobar');
|
||||
done();
|
||||
});
|
||||
|
||||
proxyServer.listen('8081');
|
||||
source.listen('8080');
|
||||
|
||||
const postData = ''.padStart(1025, 'x');
|
||||
|
||||
const postOptions = {
|
||||
hostname: '127.0.0.1',
|
||||
port: 8081,
|
||||
path: '/',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Content-Length': Buffer.byteLength(postData),
|
||||
'expect': '100-continue'
|
||||
}
|
||||
};
|
||||
|
||||
const req = http.request(postOptions, function() {});
|
||||
req.write(postData);
|
||||
req.end();
|
||||
});
|
||||
|
||||
it('should proxy the request and handle error via callback', function(done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:8080'
|
||||
});
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
function requestHandler(req, res) {
|
||||
proxy.web(req, res, function (err) {
|
||||
proxyServer.close();
|
||||
expect(err).to.be.an(Error);
|
||||
expect(err.code).to.be('ECONNREFUSED');
|
||||
done();
|
||||
});
|
||||
}
|
||||
|
||||
proxyServer.listen('8082');
|
||||
|
||||
http.request({
|
||||
hostname: '127.0.0.1',
|
||||
port: '8082',
|
||||
method: 'GET',
|
||||
}, function() {}).end();
|
||||
});
|
||||
|
||||
it('should proxy the request and handle error via event listener', function(done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:8080'
|
||||
});
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
function requestHandler(req, res) {
|
||||
proxy.once('error', function (err, errReq, errRes) {
|
||||
proxyServer.close();
|
||||
expect(err).to.be.an(Error);
|
||||
expect(errReq).to.be.equal(req);
|
||||
expect(errRes).to.be.equal(res);
|
||||
expect(err.code).to.be('ECONNREFUSED');
|
||||
done();
|
||||
});
|
||||
|
||||
proxy.web(req, res);
|
||||
}
|
||||
|
||||
proxyServer.listen('8083');
|
||||
|
||||
http.request({
|
||||
hostname: '127.0.0.1',
|
||||
port: '8083',
|
||||
method: 'GET',
|
||||
}, function() {}).end();
|
||||
});
|
||||
|
||||
it('should forward the request and handle error via event listener', function(done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
forward: 'http://127.0.0.1:8080'
|
||||
});
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
function requestHandler(req, res) {
|
||||
proxy.once('error', function (err, errReq, errRes) {
|
||||
proxyServer.close();
|
||||
expect(err).to.be.an(Error);
|
||||
expect(errReq).to.be.equal(req);
|
||||
expect(errRes).to.be.equal(res);
|
||||
expect(err.code).to.be('ECONNREFUSED');
|
||||
done();
|
||||
});
|
||||
|
||||
proxy.web(req, res);
|
||||
}
|
||||
|
||||
proxyServer.listen('8083');
|
||||
|
||||
http.request({
|
||||
hostname: '127.0.0.1',
|
||||
port: '8083',
|
||||
method: 'GET',
|
||||
}, function() {}).end();
|
||||
});
|
||||
|
||||
it('should proxy the request and handle timeout error (proxyTimeout)', function(done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:45000',
|
||||
proxyTimeout: 100
|
||||
});
|
||||
|
||||
require('net').createServer().listen(45000);
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
var started = new Date().getTime();
|
||||
function requestHandler(req, res) {
|
||||
proxy.once('error', function (err, errReq, errRes) {
|
||||
proxyServer.close();
|
||||
expect(err).to.be.an(Error);
|
||||
expect(errReq).to.be.equal(req);
|
||||
expect(errRes).to.be.equal(res);
|
||||
expect(new Date().getTime() - started).to.be.greaterThan(99);
|
||||
expect(err.code).to.be('ECONNRESET');
|
||||
done();
|
||||
});
|
||||
|
||||
proxy.web(req, res);
|
||||
}
|
||||
|
||||
proxyServer.listen('8084');
|
||||
|
||||
http.request({
|
||||
hostname: '127.0.0.1',
|
||||
port: '8084',
|
||||
method: 'GET',
|
||||
}, function() {}).end();
|
||||
});
|
||||
|
||||
it('should proxy the request and handle timeout error', function(done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:45001',
|
||||
timeout: 100
|
||||
});
|
||||
|
||||
require('net').createServer().listen(45001);
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
var cnt = 0;
|
||||
var doneOne = function() {
|
||||
cnt += 1;
|
||||
if(cnt === 2) done();
|
||||
}
|
||||
|
||||
var started = new Date().getTime();
|
||||
function requestHandler(req, res) {
|
||||
proxy.once('econnreset', function (err, errReq, errRes) {
|
||||
proxyServer.close();
|
||||
expect(err).to.be.an(Error);
|
||||
expect(errReq).to.be.equal(req);
|
||||
expect(errRes).to.be.equal(res);
|
||||
expect(err.code).to.be('ECONNRESET');
|
||||
doneOne();
|
||||
});
|
||||
|
||||
proxy.web(req, res);
|
||||
}
|
||||
|
||||
proxyServer.listen('8085');
|
||||
|
||||
var req = http.request({
|
||||
hostname: '127.0.0.1',
|
||||
port: '8085',
|
||||
method: 'GET',
|
||||
}, function() {});
|
||||
|
||||
req.on('error', function(err) {
|
||||
expect(err).to.be.an(Error);
|
||||
expect(err.code).to.be('ECONNRESET');
|
||||
expect(new Date().getTime() - started).to.be.greaterThan(99);
|
||||
doneOne();
|
||||
});
|
||||
req.end();
|
||||
});
|
||||
|
||||
it('should proxy the request and provide a proxyRes event with the request and response parameters', function(done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:8080'
|
||||
});
|
||||
|
||||
function requestHandler(req, res) {
|
||||
proxy.once('proxyRes', function (proxyRes, pReq, pRes) {
|
||||
source.close();
|
||||
proxyServer.close();
|
||||
expect(pReq).to.be.equal(req);
|
||||
expect(pRes).to.be.equal(res);
|
||||
done();
|
||||
});
|
||||
|
||||
proxy.web(req, res);
|
||||
}
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
res.end('Response');
|
||||
});
|
||||
|
||||
proxyServer.listen('8086');
|
||||
source.listen('8080');
|
||||
http.request('http://127.0.0.1:8086', function() {}).end();
|
||||
});
|
||||
|
||||
it('should proxy the request and provide and respond to manual user response when using modifyResponse', function(done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:8080',
|
||||
selfHandleResponse: true
|
||||
});
|
||||
|
||||
function requestHandler(req, res) {
|
||||
proxy.once('proxyRes', function (proxyRes, pReq, pRes) {
|
||||
proxyRes.pipe(concat(function (body) {
|
||||
expect(body.toString('utf8')).eql('Response');
|
||||
pRes.end(Buffer.from('my-custom-response'));
|
||||
}))
|
||||
});
|
||||
|
||||
proxy.web(req, res);
|
||||
}
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
res.end('Response');
|
||||
});
|
||||
|
||||
async.parallel([
|
||||
next => proxyServer.listen(8086, next),
|
||||
next => source.listen(8080, next)
|
||||
], function (err) {
|
||||
http.get('http://127.0.0.1:8086', function(res) {
|
||||
res.pipe(concat(function(body) {
|
||||
expect(body.toString('utf8')).eql('my-custom-response');
|
||||
source.close();
|
||||
proxyServer.close();
|
||||
done();
|
||||
}));
|
||||
}).once('error', done);
|
||||
})
|
||||
});
|
||||
|
||||
it('should proxy the request and handle changeOrigin option', function (done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:8080',
|
||||
changeOrigin: true
|
||||
});
|
||||
|
||||
function requestHandler(req, res) {
|
||||
proxy.web(req, res);
|
||||
}
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
source.close();
|
||||
proxyServer.close();
|
||||
expect(req.method).to.eql('GET');
|
||||
expect(req.headers.host.split(':')[1]).to.eql('8080');
|
||||
done();
|
||||
});
|
||||
|
||||
proxyServer.listen('8081');
|
||||
source.listen('8080');
|
||||
|
||||
http.request('http://127.0.0.1:8081', function() {}).end();
|
||||
});
|
||||
|
||||
it('should proxy the request with the Authorization header set', function (done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:8080',
|
||||
auth: 'user:pass'
|
||||
});
|
||||
|
||||
function requestHandler(req, res) {
|
||||
proxy.web(req, res);
|
||||
}
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
source.close();
|
||||
proxyServer.close();
|
||||
var auth = new Buffer(req.headers.authorization.split(' ')[1], 'base64');
|
||||
expect(req.method).to.eql('GET');
|
||||
expect(auth.toString()).to.eql('user:pass');
|
||||
done();
|
||||
});
|
||||
|
||||
proxyServer.listen('8081');
|
||||
source.listen('8080');
|
||||
|
||||
http.request('http://127.0.0.1:8081', function() {}).end();
|
||||
});
|
||||
|
||||
it('should proxy requests to multiple servers with different options', function (done) {
|
||||
var proxy = httpProxy.createProxyServer();
|
||||
|
||||
// proxies to two servers depending on url, rewriting the url as well
|
||||
// http://127.0.0.1:8080/s1/ -> http://127.0.0.1:8081/
|
||||
// http://127.0.0.1:8080/ -> http://127.0.0.1:8082/
|
||||
function requestHandler(req, res) {
|
||||
if (req.url.indexOf('/s1/') === 0) {
|
||||
proxy.web(req, res, {
|
||||
ignorePath: true,
|
||||
target: 'http://127.0.0.1:8081' + req.url.substring(3)
|
||||
});
|
||||
} else {
|
||||
proxy.web(req, res, {
|
||||
target: 'http://127.0.0.1:8082'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
var source1 = http.createServer(function(req, res) {
|
||||
expect(req.method).to.eql('GET');
|
||||
expect(req.headers.host.split(':')[1]).to.eql('8080');
|
||||
expect(req.url).to.eql('/test1');
|
||||
});
|
||||
|
||||
var source2 = http.createServer(function(req, res) {
|
||||
source1.close();
|
||||
source2.close();
|
||||
proxyServer.close();
|
||||
expect(req.method).to.eql('GET');
|
||||
expect(req.headers.host.split(':')[1]).to.eql('8080');
|
||||
expect(req.url).to.eql('/test2');
|
||||
done();
|
||||
});
|
||||
|
||||
proxyServer.listen('8080');
|
||||
source1.listen('8081');
|
||||
source2.listen('8082');
|
||||
|
||||
http.request('http://127.0.0.1:8080/s1/test1', function() {}).end();
|
||||
http.request('http://127.0.0.1:8080/test2', function() {}).end();
|
||||
});
|
||||
});
|
||||
|
||||
describe('#followRedirects', function () {
|
||||
it('should proxy the request follow redirects', function (done) {
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:8080',
|
||||
followRedirects: true
|
||||
});
|
||||
|
||||
function requestHandler(req, res) {
|
||||
proxy.web(req, res);
|
||||
}
|
||||
|
||||
var proxyServer = http.createServer(requestHandler);
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
|
||||
if (url.parse(req.url).pathname === '/redirect') {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.end('ok');
|
||||
}
|
||||
|
||||
res.writeHead(301, { 'Location': '/redirect' });
|
||||
res.end();
|
||||
});
|
||||
|
||||
proxyServer.listen('8081');
|
||||
source.listen('8080');
|
||||
|
||||
http.request('http://127.0.0.1:8081', function(res) {
|
||||
source.close();
|
||||
proxyServer.close();
|
||||
expect(res.statusCode).to.eql(200);
|
||||
done();
|
||||
}).end();
|
||||
});
|
||||
});
|
||||
423
test/lib-http-proxy-passes-web-outgoing-test.js
Normal file
423
test/lib-http-proxy-passes-web-outgoing-test.js
Normal file
@ -0,0 +1,423 @@
|
||||
var httpProxy = require('../lib/http-proxy/passes/web-outgoing'),
|
||||
expect = require('expect.js');
|
||||
|
||||
describe('lib/http-proxy/passes/web-outgoing.js', function () {
|
||||
describe('#setRedirectHostRewrite', function () {
|
||||
beforeEach(function() {
|
||||
this.req = {
|
||||
headers: {
|
||||
host: 'ext-auto.com'
|
||||
}
|
||||
};
|
||||
this.proxyRes = {
|
||||
statusCode: 301,
|
||||
headers: {
|
||||
location: 'http://backend.com/'
|
||||
}
|
||||
};
|
||||
this.options = {
|
||||
target: 'http://backend.com'
|
||||
};
|
||||
});
|
||||
|
||||
context('rewrites location host with hostRewrite', function() {
|
||||
beforeEach(function() {
|
||||
this.options.hostRewrite = 'ext-manual.com';
|
||||
});
|
||||
[201, 301, 302, 307, 308].forEach(function(code) {
|
||||
it('on ' + code, function() {
|
||||
this.proxyRes.statusCode = code;
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://ext-manual.com/');
|
||||
});
|
||||
});
|
||||
|
||||
it('not on 200', function() {
|
||||
this.proxyRes.statusCode = 200;
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
|
||||
});
|
||||
|
||||
it('not when hostRewrite is unset', function() {
|
||||
delete this.options.hostRewrite;
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
|
||||
});
|
||||
|
||||
it('takes precedence over autoRewrite', function() {
|
||||
this.options.autoRewrite = true;
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://ext-manual.com/');
|
||||
});
|
||||
|
||||
it('not when the redirected location does not match target host', function() {
|
||||
this.proxyRes.statusCode = 302;
|
||||
this.proxyRes.headers.location = 'http://some-other/';
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://some-other/');
|
||||
});
|
||||
|
||||
it('not when the redirected location does not match target port', function() {
|
||||
this.proxyRes.statusCode = 302;
|
||||
this.proxyRes.headers.location = 'http://backend.com:8080/';
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://backend.com:8080/');
|
||||
});
|
||||
});
|
||||
|
||||
context('rewrites location host with autoRewrite', function() {
|
||||
beforeEach(function() {
|
||||
this.options.autoRewrite = true;
|
||||
});
|
||||
[201, 301, 302, 307, 308].forEach(function(code) {
|
||||
it('on ' + code, function() {
|
||||
this.proxyRes.statusCode = code;
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://ext-auto.com/');
|
||||
});
|
||||
});
|
||||
|
||||
it('not on 200', function() {
|
||||
this.proxyRes.statusCode = 200;
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
|
||||
});
|
||||
|
||||
it('not when autoRewrite is unset', function() {
|
||||
delete this.options.autoRewrite;
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
|
||||
});
|
||||
|
||||
it('not when the redirected location does not match target host', function() {
|
||||
this.proxyRes.statusCode = 302;
|
||||
this.proxyRes.headers.location = 'http://some-other/';
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://some-other/');
|
||||
});
|
||||
|
||||
it('not when the redirected location does not match target port', function() {
|
||||
this.proxyRes.statusCode = 302;
|
||||
this.proxyRes.headers.location = 'http://backend.com:8080/';
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://backend.com:8080/');
|
||||
});
|
||||
});
|
||||
|
||||
context('rewrites location protocol with protocolRewrite', function() {
|
||||
beforeEach(function() {
|
||||
this.options.protocolRewrite = 'https';
|
||||
});
|
||||
[201, 301, 302, 307, 308].forEach(function(code) {
|
||||
it('on ' + code, function() {
|
||||
this.proxyRes.statusCode = code;
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('https://backend.com/');
|
||||
});
|
||||
});
|
||||
|
||||
it('not on 200', function() {
|
||||
this.proxyRes.statusCode = 200;
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
|
||||
});
|
||||
|
||||
it('not when protocolRewrite is unset', function() {
|
||||
delete this.options.protocolRewrite;
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
|
||||
});
|
||||
|
||||
it('works together with hostRewrite', function() {
|
||||
this.options.hostRewrite = 'ext-manual.com';
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('https://ext-manual.com/');
|
||||
});
|
||||
|
||||
it('works together with autoRewrite', function() {
|
||||
this.options.autoRewrite = true;
|
||||
httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
|
||||
expect(this.proxyRes.headers.location).to.eql('https://ext-auto.com/');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#setConnection', function () {
|
||||
it('set the right connection with 1.0 - `close`', function() {
|
||||
var proxyRes = { headers: {} };
|
||||
httpProxy.setConnection({
|
||||
httpVersion: '1.0',
|
||||
headers: {
|
||||
connection: null
|
||||
}
|
||||
}, {}, proxyRes);
|
||||
|
||||
expect(proxyRes.headers.connection).to.eql('close');
|
||||
});
|
||||
|
||||
it('set the right connection with 1.0 - req.connection', function() {
|
||||
var proxyRes = { headers: {} };
|
||||
httpProxy.setConnection({
|
||||
httpVersion: '1.0',
|
||||
headers: {
|
||||
connection: 'hey'
|
||||
}
|
||||
}, {}, proxyRes);
|
||||
|
||||
expect(proxyRes.headers.connection).to.eql('hey');
|
||||
});
|
||||
|
||||
it('set the right connection - req.connection', function() {
|
||||
var proxyRes = { headers: {} };
|
||||
httpProxy.setConnection({
|
||||
httpVersion: null,
|
||||
headers: {
|
||||
connection: 'hola'
|
||||
}
|
||||
}, {}, proxyRes);
|
||||
|
||||
expect(proxyRes.headers.connection).to.eql('hola');
|
||||
});
|
||||
|
||||
it('set the right connection - `keep-alive`', function() {
|
||||
var proxyRes = { headers: {} };
|
||||
httpProxy.setConnection({
|
||||
httpVersion: null,
|
||||
headers: {
|
||||
connection: null
|
||||
}
|
||||
}, {}, proxyRes);
|
||||
|
||||
expect(proxyRes.headers.connection).to.eql('keep-alive');
|
||||
});
|
||||
|
||||
it('don`t set connection with 2.0 if exist', function() {
|
||||
var proxyRes = { headers: {} };
|
||||
httpProxy.setConnection({
|
||||
httpVersion: '2.0',
|
||||
headers: {
|
||||
connection: 'namstey'
|
||||
}
|
||||
}, {}, proxyRes);
|
||||
|
||||
expect(proxyRes.headers.connection).to.eql(undefined);
|
||||
});
|
||||
|
||||
it('don`t set connection with 2.0 if doesn`t exist', function() {
|
||||
var proxyRes = { headers: {} };
|
||||
httpProxy.setConnection({
|
||||
httpVersion: '2.0',
|
||||
headers: {}
|
||||
}, {}, proxyRes);
|
||||
|
||||
expect(proxyRes.headers.connection).to.eql(undefined);
|
||||
})
|
||||
|
||||
});
|
||||
|
||||
describe('#writeStatusCode', function () {
|
||||
it('should write status code', function() {
|
||||
var res = {
|
||||
writeHead: function(n) {
|
||||
expect(n).to.eql(200);
|
||||
}
|
||||
};
|
||||
|
||||
httpProxy.writeStatusCode({}, res, { statusCode: 200 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('#writeHeaders', function() {
|
||||
beforeEach(function() {
|
||||
this.proxyRes = {
|
||||
headers: {
|
||||
hey: 'hello',
|
||||
how: 'are you?',
|
||||
'set-cookie': [
|
||||
'hello; domain=my.domain; path=/',
|
||||
'there; domain=my.domain; path=/'
|
||||
]
|
||||
}
|
||||
};
|
||||
this.rawProxyRes = {
|
||||
headers: {
|
||||
hey: 'hello',
|
||||
how: 'are you?',
|
||||
'set-cookie': [
|
||||
'hello; domain=my.domain; path=/',
|
||||
'there; domain=my.domain; path=/'
|
||||
]
|
||||
},
|
||||
rawHeaders: [
|
||||
'Hey', 'hello',
|
||||
'How', 'are you?',
|
||||
'Set-Cookie', 'hello; domain=my.domain; path=/',
|
||||
'Set-Cookie', 'there; domain=my.domain; path=/'
|
||||
]
|
||||
};
|
||||
this.res = {
|
||||
setHeader: function(k, v) {
|
||||
// https://nodejs.org/api/http.html#http_message_headers
|
||||
// Header names are lower-cased
|
||||
this.headers[k.toLowerCase()] = v;
|
||||
},
|
||||
headers: {}
|
||||
};
|
||||
});
|
||||
|
||||
it('writes headers', function() {
|
||||
var options = {};
|
||||
httpProxy.writeHeaders({}, this.res, this.proxyRes, options);
|
||||
|
||||
expect(this.res.headers.hey).to.eql('hello');
|
||||
expect(this.res.headers.how).to.eql('are you?');
|
||||
|
||||
expect(this.res.headers).to.have.key('set-cookie');
|
||||
expect(this.res.headers['set-cookie']).to.be.an(Array);
|
||||
expect(this.res.headers['set-cookie']).to.have.length(2);
|
||||
});
|
||||
|
||||
it('writes raw headers', function() {
|
||||
var options = {};
|
||||
httpProxy.writeHeaders({}, this.res, this.rawProxyRes, options);
|
||||
|
||||
expect(this.res.headers.hey).to.eql('hello');
|
||||
expect(this.res.headers.how).to.eql('are you?');
|
||||
|
||||
expect(this.res.headers).to.have.key('set-cookie');
|
||||
expect(this.res.headers['set-cookie']).to.be.an(Array);
|
||||
expect(this.res.headers['set-cookie']).to.have.length(2);
|
||||
});
|
||||
|
||||
it('rewrites path', function() {
|
||||
var options = {
|
||||
cookiePathRewrite: '/dummyPath'
|
||||
};
|
||||
|
||||
httpProxy.writeHeaders({}, this.res, this.proxyRes, options);
|
||||
|
||||
expect(this.res.headers['set-cookie'])
|
||||
.to.contain('hello; domain=my.domain; path=/dummyPath');
|
||||
});
|
||||
|
||||
it('does not rewrite path', function() {
|
||||
var options = {};
|
||||
|
||||
httpProxy.writeHeaders({}, this.res, this.proxyRes, options);
|
||||
|
||||
expect(this.res.headers['set-cookie'])
|
||||
.to.contain('hello; domain=my.domain; path=/');
|
||||
});
|
||||
|
||||
it('removes path', function() {
|
||||
var options = {
|
||||
cookiePathRewrite: ''
|
||||
};
|
||||
|
||||
httpProxy.writeHeaders({}, this.res, this.proxyRes, options);
|
||||
|
||||
expect(this.res.headers['set-cookie'])
|
||||
.to.contain('hello; domain=my.domain');
|
||||
});
|
||||
|
||||
it('does not rewrite domain', function() {
|
||||
var options = {};
|
||||
|
||||
httpProxy.writeHeaders({}, this.res, this.proxyRes, options);
|
||||
|
||||
expect(this.res.headers['set-cookie'])
|
||||
.to.contain('hello; domain=my.domain; path=/');
|
||||
});
|
||||
|
||||
it('rewrites domain', function() {
|
||||
var options = {
|
||||
cookieDomainRewrite: 'my.new.domain'
|
||||
};
|
||||
|
||||
httpProxy.writeHeaders({}, this.res, this.proxyRes, options);
|
||||
|
||||
expect(this.res.headers['set-cookie'])
|
||||
.to.contain('hello; domain=my.new.domain; path=/');
|
||||
});
|
||||
|
||||
it('removes domain', function() {
|
||||
var options = {
|
||||
cookieDomainRewrite: ''
|
||||
};
|
||||
|
||||
httpProxy.writeHeaders({}, this.res, this.proxyRes, options);
|
||||
|
||||
expect(this.res.headers['set-cookie'])
|
||||
.to.contain('hello; path=/');
|
||||
});
|
||||
|
||||
it('rewrites headers with advanced configuration', function() {
|
||||
var options = {
|
||||
cookieDomainRewrite: {
|
||||
'*': '',
|
||||
'my.old.domain': 'my.new.domain',
|
||||
'my.special.domain': 'my.special.domain'
|
||||
}
|
||||
};
|
||||
this.proxyRes.headers['set-cookie'] = [
|
||||
'hello-on-my.domain; domain=my.domain; path=/',
|
||||
'hello-on-my.old.domain; domain=my.old.domain; path=/',
|
||||
'hello-on-my.special.domain; domain=my.special.domain; path=/'
|
||||
];
|
||||
httpProxy.writeHeaders({}, this.res, this.proxyRes, options);
|
||||
|
||||
expect(this.res.headers['set-cookie'])
|
||||
.to.contain('hello-on-my.domain; path=/');
|
||||
expect(this.res.headers['set-cookie'])
|
||||
.to.contain('hello-on-my.old.domain; domain=my.new.domain; path=/');
|
||||
expect(this.res.headers['set-cookie'])
|
||||
.to.contain('hello-on-my.special.domain; domain=my.special.domain; path=/');
|
||||
});
|
||||
|
||||
it('rewrites raw headers with advanced configuration', function() {
|
||||
var options = {
|
||||
cookieDomainRewrite: {
|
||||
'*': '',
|
||||
'my.old.domain': 'my.new.domain',
|
||||
'my.special.domain': 'my.special.domain'
|
||||
}
|
||||
};
|
||||
this.rawProxyRes.headers['set-cookie'] = [
|
||||
'hello-on-my.domain; domain=my.domain; path=/',
|
||||
'hello-on-my.old.domain; domain=my.old.domain; path=/',
|
||||
'hello-on-my.special.domain; domain=my.special.domain; path=/'
|
||||
];
|
||||
this.rawProxyRes.rawHeaders = this.rawProxyRes.rawHeaders.concat([
|
||||
'Set-Cookie',
|
||||
'hello-on-my.domain; domain=my.domain; path=/',
|
||||
'Set-Cookie',
|
||||
'hello-on-my.old.domain; domain=my.old.domain; path=/',
|
||||
'Set-Cookie',
|
||||
'hello-on-my.special.domain; domain=my.special.domain; path=/'
|
||||
]);
|
||||
httpProxy.writeHeaders({}, this.res, this.rawProxyRes, options);
|
||||
|
||||
expect(this.res.headers['set-cookie'])
|
||||
.to.contain('hello-on-my.domain; path=/');
|
||||
expect(this.res.headers['set-cookie'])
|
||||
.to.contain('hello-on-my.old.domain; domain=my.new.domain; path=/');
|
||||
expect(this.res.headers['set-cookie'])
|
||||
.to.contain('hello-on-my.special.domain; domain=my.special.domain; path=/');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('#removeChunked', function() {
|
||||
var proxyRes = {
|
||||
headers: {
|
||||
'transfer-encoding': 'hello'
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
httpProxy.removeChunked({ httpVersion: '1.0' }, {}, proxyRes);
|
||||
|
||||
expect(proxyRes.headers['transfer-encoding']).to.eql(undefined);
|
||||
});
|
||||
|
||||
});
|
||||
120
test/lib-http-proxy-passes-ws-incoming-test.js
Normal file
120
test/lib-http-proxy-passes-ws-incoming-test.js
Normal file
@ -0,0 +1,120 @@
|
||||
var httpProxy = require('../lib/http-proxy/passes/ws-incoming'),
|
||||
expect = require('expect.js');
|
||||
|
||||
describe('lib/http-proxy/passes/ws-incoming.js', function () {
|
||||
describe('#checkMethodAndHeader', function () {
|
||||
it('should drop non-GET connections', function () {
|
||||
var destroyCalled = false,
|
||||
stubRequest = {
|
||||
method: 'DELETE',
|
||||
headers: {}
|
||||
},
|
||||
stubSocket = {
|
||||
destroy: function () {
|
||||
// Simulate Socket.destroy() method when call
|
||||
destroyCalled = true;
|
||||
}
|
||||
}
|
||||
returnValue = httpProxy.checkMethodAndHeader(stubRequest, stubSocket);
|
||||
expect(returnValue).to.be(true);
|
||||
expect(destroyCalled).to.be(true);
|
||||
})
|
||||
|
||||
it('should drop connections when no upgrade header', function () {
|
||||
var destroyCalled = false,
|
||||
stubRequest = {
|
||||
method: 'GET',
|
||||
headers: {}
|
||||
},
|
||||
stubSocket = {
|
||||
destroy: function () {
|
||||
// Simulate Socket.destroy() method when call
|
||||
destroyCalled = true;
|
||||
}
|
||||
}
|
||||
returnValue = httpProxy.checkMethodAndHeader(stubRequest, stubSocket);
|
||||
expect(returnValue).to.be(true);
|
||||
expect(destroyCalled).to.be(true);
|
||||
})
|
||||
|
||||
it('should drop connections when upgrade header is different of `websocket`', function () {
|
||||
var destroyCalled = false,
|
||||
stubRequest = {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
upgrade: 'anotherprotocol'
|
||||
}
|
||||
},
|
||||
stubSocket = {
|
||||
destroy: function () {
|
||||
// Simulate Socket.destroy() method when call
|
||||
destroyCalled = true;
|
||||
}
|
||||
}
|
||||
returnValue = httpProxy.checkMethodAndHeader(stubRequest, stubSocket);
|
||||
expect(returnValue).to.be(true);
|
||||
expect(destroyCalled).to.be(true);
|
||||
})
|
||||
|
||||
it('should return nothing when all is ok', function () {
|
||||
var destroyCalled = false,
|
||||
stubRequest = {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
upgrade: 'websocket'
|
||||
}
|
||||
},
|
||||
stubSocket = {
|
||||
destroy: function () {
|
||||
// Simulate Socket.destroy() method when call
|
||||
destroyCalled = true;
|
||||
}
|
||||
}
|
||||
returnValue = httpProxy.checkMethodAndHeader(stubRequest, stubSocket);
|
||||
expect(returnValue).to.be(undefined);
|
||||
expect(destroyCalled).to.be(false);
|
||||
})
|
||||
});
|
||||
|
||||
describe('#XHeaders', function () {
|
||||
it('return if no forward request', function () {
|
||||
var returnValue = httpProxy.XHeaders({}, {}, {});
|
||||
expect(returnValue).to.be(undefined);
|
||||
});
|
||||
|
||||
it('set the correct x-forwarded-* headers from req.connection', function () {
|
||||
var stubRequest = {
|
||||
connection: {
|
||||
remoteAddress: '192.168.1.2',
|
||||
remotePort: '8080'
|
||||
},
|
||||
headers: {
|
||||
host: '192.168.1.2:8080'
|
||||
}
|
||||
}
|
||||
httpProxy.XHeaders(stubRequest, {}, { xfwd: true });
|
||||
expect(stubRequest.headers['x-forwarded-for']).to.be('192.168.1.2');
|
||||
expect(stubRequest.headers['x-forwarded-port']).to.be('8080');
|
||||
expect(stubRequest.headers['x-forwarded-proto']).to.be('ws');
|
||||
});
|
||||
|
||||
it('set the correct x-forwarded-* headers from req.socket', function () {
|
||||
var stubRequest = {
|
||||
socket: {
|
||||
remoteAddress: '192.168.1.3',
|
||||
remotePort: '8181'
|
||||
},
|
||||
connection: {
|
||||
pair: true
|
||||
},
|
||||
headers: {
|
||||
host: '192.168.1.3:8181'
|
||||
}
|
||||
};
|
||||
httpProxy.XHeaders(stubRequest, {}, { xfwd: true });
|
||||
expect(stubRequest.headers['x-forwarded-for']).to.be('192.168.1.3');
|
||||
expect(stubRequest.headers['x-forwarded-port']).to.be('8181');
|
||||
expect(stubRequest.headers['x-forwarded-proto']).to.be('wss');
|
||||
});
|
||||
});
|
||||
});
|
||||
639
test/lib-http-proxy-test.js
Normal file
639
test/lib-http-proxy-test.js
Normal file
@ -0,0 +1,639 @@
|
||||
var httpProxy = require('../lib/http-proxy'),
|
||||
expect = require('expect.js'),
|
||||
http = require('http'),
|
||||
net = require('net'),
|
||||
ws = require('ws'),
|
||||
io = require('socket.io'),
|
||||
SSE = require('sse'),
|
||||
ioClient = require('socket.io-client');
|
||||
|
||||
//
|
||||
// Expose a port number generator.
|
||||
// thanks to @3rd-Eden
|
||||
//
|
||||
var initialPort = 1024, gen = {};
|
||||
Object.defineProperty(gen, 'port', {
|
||||
get: function get() {
|
||||
return initialPort++;
|
||||
}
|
||||
});
|
||||
|
||||
describe('lib/http-proxy.js', function() {
|
||||
describe('#createProxyServer', function() {
|
||||
it.skip('should throw without options', function() {
|
||||
var error;
|
||||
try {
|
||||
httpProxy.createProxyServer();
|
||||
} catch(e) {
|
||||
error = e;
|
||||
}
|
||||
|
||||
expect(error).to.be.an(Error);
|
||||
})
|
||||
|
||||
it('should return an object otherwise', function() {
|
||||
var obj = httpProxy.createProxyServer({
|
||||
target: 'http://www.google.com:80'
|
||||
});
|
||||
|
||||
expect(obj.web).to.be.a(Function);
|
||||
expect(obj.ws).to.be.a(Function);
|
||||
expect(obj.listen).to.be.a(Function);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#createProxyServer with forward options and using web-incoming passes', function () {
|
||||
it('should pipe the request using web-incoming#stream method', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
forward: 'http://127.0.0.1:' + ports.source
|
||||
}).listen(ports.proxy);
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
expect(req.method).to.eql('GET');
|
||||
expect(req.headers.host.split(':')[1]).to.eql(ports.proxy);
|
||||
source.close();
|
||||
proxy.close();
|
||||
done();
|
||||
});
|
||||
|
||||
source.listen(ports.source);
|
||||
http.request('http://127.0.0.1:' + ports.proxy, function() {}).end();
|
||||
})
|
||||
});
|
||||
|
||||
describe('#createProxyServer using the web-incoming passes', function () {
|
||||
it('should proxy sse', function(done){
|
||||
var ports = { source: gen.port, proxy: gen.port },
|
||||
proxy = httpProxy.createProxyServer({
|
||||
target: 'http://localhost:' + ports.source,
|
||||
}),
|
||||
proxyServer = proxy.listen(ports.proxy),
|
||||
source = http.createServer(),
|
||||
sse = new SSE(source, {path: '/'});
|
||||
|
||||
sse.on('connection', function(client) {
|
||||
client.send('Hello over SSE');
|
||||
client.close();
|
||||
});
|
||||
|
||||
source.listen(ports.source);
|
||||
|
||||
var options = {
|
||||
hostname: 'localhost',
|
||||
port: ports.proxy,
|
||||
};
|
||||
|
||||
var req = http.request(options, function(res) {
|
||||
var streamData = '';
|
||||
res.on('data', function (chunk) {
|
||||
streamData += chunk.toString('utf8');
|
||||
});
|
||||
res.on('end', function (chunk) {
|
||||
expect(streamData).to.equal(':ok\n\ndata: Hello over SSE\n\n');
|
||||
source.close();
|
||||
proxy.close();
|
||||
done();
|
||||
});
|
||||
}).end();
|
||||
});
|
||||
|
||||
it('should make the request on pipe and finish it', function(done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:' + ports.source
|
||||
}).listen(ports.proxy);
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
expect(req.method).to.eql('POST');
|
||||
expect(req.headers['x-forwarded-for']).to.eql('127.0.0.1');
|
||||
expect(req.headers.host.split(':')[1]).to.eql(ports.proxy);
|
||||
source.close();
|
||||
proxy.close();
|
||||
done();
|
||||
});
|
||||
|
||||
source.listen(ports.source);
|
||||
|
||||
http.request({
|
||||
hostname: '127.0.0.1',
|
||||
port: ports.proxy,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'x-forwarded-for': '127.0.0.1'
|
||||
}
|
||||
}, function() {}).end();
|
||||
});
|
||||
});
|
||||
|
||||
describe('#createProxyServer using the web-incoming passes', function () {
|
||||
it('should make the request, handle response and finish it', function(done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:' + ports.source,
|
||||
preserveHeaderKeyCase: true
|
||||
}).listen(ports.proxy);
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
expect(req.method).to.eql('GET');
|
||||
expect(req.headers.host.split(':')[1]).to.eql(ports.proxy);
|
||||
res.writeHead(200, {'Content-Type': 'text/plain'})
|
||||
res.end('Hello from ' + source.address().port);
|
||||
});
|
||||
|
||||
source.listen(ports.source);
|
||||
|
||||
http.request({
|
||||
hostname: '127.0.0.1',
|
||||
port: ports.proxy,
|
||||
method: 'GET'
|
||||
}, function(res) {
|
||||
expect(res.statusCode).to.eql(200);
|
||||
expect(res.headers['content-type']).to.eql('text/plain');
|
||||
if (res.rawHeaders != undefined) {
|
||||
expect(res.rawHeaders.indexOf('Content-Type')).not.to.eql(-1);
|
||||
expect(res.rawHeaders.indexOf('text/plain')).not.to.eql(-1);
|
||||
}
|
||||
|
||||
res.on('data', function (data) {
|
||||
expect(data.toString()).to.eql('Hello from ' + ports.source);
|
||||
});
|
||||
|
||||
res.on('end', function () {
|
||||
source.close();
|
||||
proxy.close();
|
||||
done();
|
||||
});
|
||||
}).end();
|
||||
});
|
||||
});
|
||||
|
||||
describe('#createProxyServer() method with error response', function () {
|
||||
it('should make the request and emit the error event', function(done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:' + ports.source
|
||||
});
|
||||
|
||||
proxy.on('error', function (err) {
|
||||
expect(err).to.be.an(Error);
|
||||
expect(err.code).to.be('ECONNREFUSED');
|
||||
proxy.close();
|
||||
done();
|
||||
})
|
||||
|
||||
proxy.listen(ports.proxy);
|
||||
|
||||
http.request({
|
||||
hostname: '127.0.0.1',
|
||||
port: ports.proxy,
|
||||
method: 'GET',
|
||||
}, function() {}).end();
|
||||
});
|
||||
});
|
||||
|
||||
describe('#createProxyServer setting the correct timeout value', function () {
|
||||
it('should hang up the socket at the timeout', function (done) {
|
||||
this.timeout(30);
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:' + ports.source,
|
||||
timeout: 3
|
||||
}).listen(ports.proxy);
|
||||
|
||||
proxy.on('error', function (e) {
|
||||
expect(e).to.be.an(Error);
|
||||
expect(e.code).to.be.eql('ECONNRESET');
|
||||
});
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
setTimeout(function () {
|
||||
res.end('At this point the socket should be closed');
|
||||
}, 5)
|
||||
});
|
||||
|
||||
source.listen(ports.source);
|
||||
|
||||
var testReq = http.request({
|
||||
hostname: '127.0.0.1',
|
||||
port: ports.proxy,
|
||||
method: 'GET',
|
||||
}, function() {});
|
||||
|
||||
testReq.on('error', function (e) {
|
||||
expect(e).to.be.an(Error);
|
||||
expect(e.code).to.be.eql('ECONNRESET');
|
||||
proxy.close();
|
||||
source.close();
|
||||
done();
|
||||
});
|
||||
|
||||
testReq.end();
|
||||
});
|
||||
});
|
||||
|
||||
describe('#createProxyServer with xfwd option', function () {
|
||||
it('should not throw on empty http host header', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
forward: 'http://127.0.0.1:' + ports.source,
|
||||
xfwd: true
|
||||
}).listen(ports.proxy);
|
||||
|
||||
var source = http.createServer(function(req, res) {
|
||||
expect(req.method).to.eql('GET');
|
||||
expect(req.headers.host.split(':')[1]).to.eql(ports.source);
|
||||
source.close();
|
||||
proxy.close();
|
||||
done();
|
||||
});
|
||||
|
||||
source.listen(ports.source);
|
||||
|
||||
var socket = net.connect({port: ports.proxy}, function()
|
||||
{
|
||||
socket.write('GET / HTTP/1.0\r\n\r\n');
|
||||
});
|
||||
|
||||
// handle errors
|
||||
socket.on('error', function()
|
||||
{
|
||||
expect.fail('Unexpected socket error');
|
||||
});
|
||||
|
||||
socket.on('data', function(data)
|
||||
{
|
||||
socket.end();
|
||||
});
|
||||
|
||||
socket.on('end', function()
|
||||
{
|
||||
expect('Socket to finish').to.be.ok();
|
||||
});
|
||||
|
||||
// http.request('http://127.0.0.1:' + ports.proxy, function() {}).end();
|
||||
})
|
||||
});
|
||||
|
||||
// describe('#createProxyServer using the web-incoming passes', function () {
|
||||
// it('should emit events correctly', function(done) {
|
||||
// var proxy = httpProxy.createProxyServer({
|
||||
// target: 'http://127.0.0.1:8080'
|
||||
// }),
|
||||
|
||||
// proxyServer = proxy.listen('8081'),
|
||||
|
||||
// source = http.createServer(function(req, res) {
|
||||
// expect(req.method).to.eql('GET');
|
||||
// expect(req.headers.host.split(':')[1]).to.eql('8081');
|
||||
// res.writeHead(200, {'Content-Type': 'text/plain'})
|
||||
// res.end('Hello from ' + source.address().port);
|
||||
// }),
|
||||
|
||||
// events = [];
|
||||
|
||||
// source.listen('8080');
|
||||
|
||||
// proxy.ee.on('http-proxy:**', function (uno, dos, tres) {
|
||||
// events.push(this.event);
|
||||
// })
|
||||
|
||||
// http.request({
|
||||
// hostname: '127.0.0.1',
|
||||
// port: '8081',
|
||||
// method: 'GET',
|
||||
// }, function(res) {
|
||||
// expect(res.statusCode).to.eql(200);
|
||||
|
||||
// res.on('data', function (data) {
|
||||
// expect(data.toString()).to.eql('Hello from 8080');
|
||||
// });
|
||||
|
||||
// res.on('end', function () {
|
||||
// expect(events).to.contain('http-proxy:outgoing:web:begin');
|
||||
// expect(events).to.contain('http-proxy:outgoing:web:end');
|
||||
// source.close();
|
||||
// proxyServer.close();
|
||||
// done();
|
||||
// });
|
||||
// }).end();
|
||||
// });
|
||||
// });
|
||||
|
||||
describe('#createProxyServer using the ws-incoming passes', function () {
|
||||
it('should proxy the websockets stream', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'ws://127.0.0.1:' + ports.source,
|
||||
ws: true
|
||||
}),
|
||||
proxyServer = proxy.listen(ports.proxy),
|
||||
destiny = new ws.Server({ port: ports.source }, function () {
|
||||
var client = new ws('ws://127.0.0.1:' + ports.proxy);
|
||||
|
||||
client.on('open', function () {
|
||||
client.send('hello there');
|
||||
});
|
||||
|
||||
client.on('message', function (msg) {
|
||||
expect(msg).to.be('Hello over websockets');
|
||||
client.close();
|
||||
proxyServer.close();
|
||||
destiny.close();
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
destiny.on('connection', function (socket) {
|
||||
socket.on('message', function (msg) {
|
||||
expect(msg).to.be('hello there');
|
||||
socket.send('Hello over websockets');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should emit error on proxy error', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
// note: we don't ever listen on this port
|
||||
target: 'ws://127.0.0.1:' + ports.source,
|
||||
ws: true
|
||||
}),
|
||||
proxyServer = proxy.listen(ports.proxy),
|
||||
client = new ws('ws://127.0.0.1:' + ports.proxy);
|
||||
|
||||
client.on('open', function () {
|
||||
client.send('hello there');
|
||||
});
|
||||
|
||||
var count = 0;
|
||||
function maybe_done () {
|
||||
count += 1;
|
||||
if (count === 2) done();
|
||||
}
|
||||
|
||||
client.on('error', function (err) {
|
||||
expect(err).to.be.an(Error);
|
||||
expect(err.code).to.be('ECONNRESET');
|
||||
maybe_done();
|
||||
});
|
||||
|
||||
proxy.on('error', function (err) {
|
||||
expect(err).to.be.an(Error);
|
||||
expect(err.code).to.be('ECONNREFUSED');
|
||||
proxyServer.close();
|
||||
maybe_done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should close client socket if upstream is closed before upgrade', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var server = http.createServer();
|
||||
server.on('upgrade', function (req, socket, head) {
|
||||
var response = [
|
||||
'HTTP/1.1 404 Not Found',
|
||||
'Content-type: text/html',
|
||||
'',
|
||||
''
|
||||
];
|
||||
socket.write(response.join('\r\n'));
|
||||
socket.end();
|
||||
});
|
||||
server.listen(ports.source);
|
||||
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
// note: we don't ever listen on this port
|
||||
target: 'ws://127.0.0.1:' + ports.source,
|
||||
ws: true
|
||||
}),
|
||||
proxyServer = proxy.listen(ports.proxy),
|
||||
client = new ws('ws://127.0.0.1:' + ports.proxy);
|
||||
|
||||
client.on('open', function () {
|
||||
client.send('hello there');
|
||||
});
|
||||
|
||||
client.on('error', function (err) {
|
||||
expect(err).to.be.an(Error);
|
||||
proxyServer.close();
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should proxy a socket.io stream', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port },
|
||||
proxy = httpProxy.createProxyServer({
|
||||
target: 'ws://127.0.0.1:' + ports.source,
|
||||
ws: true
|
||||
}),
|
||||
proxyServer = proxy.listen(ports.proxy),
|
||||
server = http.createServer(),
|
||||
destiny = io.listen(server);
|
||||
|
||||
function startSocketIo() {
|
||||
var client = ioClient.connect('ws://127.0.0.1:' + ports.proxy);
|
||||
|
||||
client.on('connect', function () {
|
||||
client.emit('incoming', 'hello there');
|
||||
});
|
||||
|
||||
client.on('outgoing', function (data) {
|
||||
expect(data).to.be('Hello over websockets');
|
||||
proxyServer.close();
|
||||
server.close();
|
||||
done();
|
||||
});
|
||||
}
|
||||
server.listen(ports.source);
|
||||
server.on('listening', startSocketIo);
|
||||
|
||||
destiny.sockets.on('connection', function (socket) {
|
||||
socket.on('incoming', function (msg) {
|
||||
expect(msg).to.be('hello there');
|
||||
socket.emit('outgoing', 'Hello over websockets');
|
||||
});
|
||||
})
|
||||
});
|
||||
|
||||
|
||||
it('should emit open and close events when socket.io client connects and disconnects', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'ws://127.0.0.1:' + ports.source,
|
||||
ws: true
|
||||
});
|
||||
var proxyServer = proxy.listen(ports.proxy);
|
||||
var server = http.createServer();
|
||||
var destiny = io.listen(server);
|
||||
|
||||
function startSocketIo() {
|
||||
var client = ioClient.connect('ws://127.0.0.1:' + ports.proxy, {rejectUnauthorized: null});
|
||||
client.on('connect', function () {
|
||||
client.disconnect();
|
||||
});
|
||||
}
|
||||
var count = 0;
|
||||
|
||||
proxyServer.on('open', function() {
|
||||
count += 1;
|
||||
|
||||
});
|
||||
|
||||
proxyServer.on('close', function() {
|
||||
proxyServer.close();
|
||||
server.close();
|
||||
destiny.close();
|
||||
if (count == 1) { done(); }
|
||||
});
|
||||
|
||||
server.listen(ports.source);
|
||||
server.on('listening', startSocketIo);
|
||||
|
||||
});
|
||||
|
||||
it('should pass all set-cookie headers to client', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'ws://127.0.0.1:' + ports.source,
|
||||
ws: true
|
||||
}),
|
||||
proxyServer = proxy.listen(ports.proxy),
|
||||
destiny = new ws.Server({ port: ports.source }, function () {
|
||||
var key = new Buffer(Math.random().toString()).toString('base64');
|
||||
|
||||
var requestOptions = {
|
||||
port: ports.proxy,
|
||||
host: '127.0.0.1',
|
||||
headers: {
|
||||
'Connection': 'Upgrade',
|
||||
'Upgrade': 'websocket',
|
||||
'Host': 'ws://127.0.0.1',
|
||||
'Sec-WebSocket-Version': 13,
|
||||
'Sec-WebSocket-Key': key
|
||||
}
|
||||
};
|
||||
|
||||
var req = http.request(requestOptions);
|
||||
|
||||
req.on('upgrade', function (res, socket, upgradeHead) {
|
||||
expect(res.headers['set-cookie'].length).to.be(2);
|
||||
done();
|
||||
});
|
||||
|
||||
req.end();
|
||||
});
|
||||
|
||||
destiny.on('headers', function (headers) {
|
||||
headers.push('Set-Cookie: test1=test1');
|
||||
headers.push('Set-Cookie: test2=test2');
|
||||
});
|
||||
});
|
||||
|
||||
it('should detect a proxyReq event and modify headers', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port },
|
||||
proxy,
|
||||
proxyServer,
|
||||
destiny;
|
||||
|
||||
proxy = httpProxy.createProxyServer({
|
||||
target: 'ws://127.0.0.1:' + ports.source,
|
||||
ws: true
|
||||
});
|
||||
|
||||
proxy.on('proxyReqWs', function(proxyReq, req, socket, options, head) {
|
||||
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
|
||||
});
|
||||
|
||||
proxyServer = proxy.listen(ports.proxy);
|
||||
|
||||
destiny = new ws.Server({ port: ports.source }, function () {
|
||||
var client = new ws('ws://127.0.0.1:' + ports.proxy);
|
||||
|
||||
client.on('open', function () {
|
||||
client.send('hello there');
|
||||
});
|
||||
|
||||
client.on('message', function (msg) {
|
||||
expect(msg).to.be('Hello over websockets');
|
||||
client.close();
|
||||
proxyServer.close();
|
||||
destiny.close();
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
destiny.on('connection', function (socket, upgradeReq) {
|
||||
expect(upgradeReq.headers['x-special-proxy-header']).to.eql('foobar');
|
||||
|
||||
socket.on('message', function (msg) {
|
||||
expect(msg).to.be('hello there');
|
||||
socket.send('Hello over websockets');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should forward frames with single frame payload (including on node 4.x)', function (done) {
|
||||
var payload = Array(65529).join('0');
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'ws://127.0.0.1:' + ports.source,
|
||||
ws: true
|
||||
}),
|
||||
proxyServer = proxy.listen(ports.proxy),
|
||||
destiny = new ws.Server({ port: ports.source }, function () {
|
||||
var client = new ws('ws://127.0.0.1:' + ports.proxy);
|
||||
|
||||
client.on('open', function () {
|
||||
client.send(payload);
|
||||
});
|
||||
|
||||
client.on('message', function (msg) {
|
||||
expect(msg).to.be('Hello over websockets');
|
||||
client.close();
|
||||
proxyServer.close();
|
||||
destiny.close();
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
destiny.on('connection', function (socket) {
|
||||
socket.on('message', function (msg) {
|
||||
expect(msg).to.be(payload);
|
||||
socket.send('Hello over websockets');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should forward continuation frames with big payload (including on node 4.x)', function (done) {
|
||||
var payload = Array(65530).join('0');
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'ws://127.0.0.1:' + ports.source,
|
||||
ws: true
|
||||
}),
|
||||
proxyServer = proxy.listen(ports.proxy),
|
||||
destiny = new ws.Server({ port: ports.source }, function () {
|
||||
var client = new ws('ws://127.0.0.1:' + ports.proxy);
|
||||
|
||||
client.on('open', function () {
|
||||
client.send(payload);
|
||||
});
|
||||
|
||||
client.on('message', function (msg) {
|
||||
expect(msg).to.be('Hello over websockets');
|
||||
client.close();
|
||||
proxyServer.close();
|
||||
destiny.close();
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
destiny.on('connection', function (socket) {
|
||||
socket.on('message', function (msg) {
|
||||
expect(msg).to.be(payload);
|
||||
socket.send('Hello over websockets');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
233
test/lib-https-proxy-test.js
Normal file
233
test/lib-https-proxy-test.js
Normal file
@ -0,0 +1,233 @@
|
||||
var httpProxy = require('../lib/http-proxy'),
|
||||
semver = require('semver'),
|
||||
expect = require('expect.js'),
|
||||
http = require('http')
|
||||
https = require('https'),
|
||||
path = require('path'),
|
||||
fs = require('fs');
|
||||
|
||||
//
|
||||
// Expose a port number generator.
|
||||
// thanks to @3rd-Eden
|
||||
//
|
||||
var initialPort = 1024, gen = {};
|
||||
Object.defineProperty(gen, 'port', {
|
||||
get: function get() {
|
||||
return initialPort++;
|
||||
}
|
||||
});
|
||||
|
||||
describe('lib/http-proxy.js', function() {
|
||||
describe('HTTPS #createProxyServer', function() {
|
||||
describe('HTTPS to HTTP', function () {
|
||||
it('should proxy the request en send back the response', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var source = http.createServer(function(req, res) {
|
||||
expect(req.method).to.eql('GET');
|
||||
expect(req.headers.host.split(':')[1]).to.eql(ports.proxy);
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.end('Hello from ' + ports.source);
|
||||
});
|
||||
|
||||
source.listen(ports.source);
|
||||
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'http://127.0.0.1:' + ports.source,
|
||||
ssl: {
|
||||
key: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-key.pem')),
|
||||
cert: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-cert.pem')),
|
||||
ciphers: 'AES128-GCM-SHA256',
|
||||
}
|
||||
}).listen(ports.proxy);
|
||||
|
||||
https.request({
|
||||
host: 'localhost',
|
||||
port: ports.proxy,
|
||||
path: '/',
|
||||
method: 'GET',
|
||||
rejectUnauthorized: false
|
||||
}, function(res) {
|
||||
expect(res.statusCode).to.eql(200);
|
||||
|
||||
res.on('data', function (data) {
|
||||
expect(data.toString()).to.eql('Hello from ' + ports.source);
|
||||
});
|
||||
|
||||
res.on('end', function () {
|
||||
source.close();
|
||||
proxy.close();
|
||||
done();
|
||||
})
|
||||
}).end();
|
||||
})
|
||||
});
|
||||
describe('HTTP to HTTPS', function () {
|
||||
it('should proxy the request en send back the response', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var source = https.createServer({
|
||||
key: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-key.pem')),
|
||||
cert: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-cert.pem')),
|
||||
ciphers: 'AES128-GCM-SHA256',
|
||||
}, function (req, res) {
|
||||
expect(req.method).to.eql('GET');
|
||||
expect(req.headers.host.split(':')[1]).to.eql(ports.proxy);
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.end('Hello from ' + ports.source);
|
||||
});
|
||||
|
||||
source.listen(ports.source);
|
||||
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'https://127.0.0.1:' + ports.source,
|
||||
// Allow to use SSL self signed
|
||||
secure: false
|
||||
}).listen(ports.proxy);
|
||||
|
||||
http.request({
|
||||
hostname: '127.0.0.1',
|
||||
port: ports.proxy,
|
||||
method: 'GET'
|
||||
}, function(res) {
|
||||
expect(res.statusCode).to.eql(200);
|
||||
|
||||
res.on('data', function (data) {
|
||||
expect(data.toString()).to.eql('Hello from ' + ports.source);
|
||||
});
|
||||
|
||||
res.on('end', function () {
|
||||
source.close();
|
||||
proxy.close();
|
||||
done();
|
||||
});
|
||||
}).end();
|
||||
})
|
||||
})
|
||||
describe('HTTPS to HTTPS', function () {
|
||||
it('should proxy the request en send back the response', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var source = https.createServer({
|
||||
key: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-key.pem')),
|
||||
cert: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-cert.pem')),
|
||||
ciphers: 'AES128-GCM-SHA256',
|
||||
}, function(req, res) {
|
||||
expect(req.method).to.eql('GET');
|
||||
expect(req.headers.host.split(':')[1]).to.eql(ports.proxy);
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.end('Hello from ' + ports.source);
|
||||
});
|
||||
|
||||
source.listen(ports.source);
|
||||
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'https://127.0.0.1:' + ports.source,
|
||||
ssl: {
|
||||
key: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-key.pem')),
|
||||
cert: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-cert.pem')),
|
||||
ciphers: 'AES128-GCM-SHA256',
|
||||
},
|
||||
secure: false
|
||||
}).listen(ports.proxy);
|
||||
|
||||
https.request({
|
||||
host: 'localhost',
|
||||
port: ports.proxy,
|
||||
path: '/',
|
||||
method: 'GET',
|
||||
rejectUnauthorized: false
|
||||
}, function(res) {
|
||||
expect(res.statusCode).to.eql(200);
|
||||
|
||||
res.on('data', function (data) {
|
||||
expect(data.toString()).to.eql('Hello from ' + ports.source);
|
||||
});
|
||||
|
||||
res.on('end', function () {
|
||||
source.close();
|
||||
proxy.close();
|
||||
done();
|
||||
})
|
||||
}).end();
|
||||
})
|
||||
});
|
||||
describe('HTTPS not allow SSL self signed', function () {
|
||||
it('should fail with error', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var source = https.createServer({
|
||||
key: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-key.pem')),
|
||||
cert: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-cert.pem')),
|
||||
ciphers: 'AES128-GCM-SHA256',
|
||||
}).listen(ports.source);
|
||||
|
||||
var proxy = httpProxy.createProxyServer({
|
||||
target: 'https://127.0.0.1:' + ports.source,
|
||||
secure: true
|
||||
});
|
||||
|
||||
proxy.listen(ports.proxy);
|
||||
|
||||
proxy.on('error', function (err, req, res) {
|
||||
expect(err).to.be.an(Error);
|
||||
if (semver.gt(process.versions.node, '0.12.0')) {
|
||||
expect(err.toString()).to.be('Error: unable to verify the first certificate')
|
||||
} else {
|
||||
expect(err.toString()).to.be('Error: DEPTH_ZERO_SELF_SIGNED_CERT')
|
||||
}
|
||||
done();
|
||||
})
|
||||
|
||||
http.request({
|
||||
hostname: '127.0.0.1',
|
||||
port: ports.proxy,
|
||||
method: 'GET'
|
||||
}).end();
|
||||
})
|
||||
})
|
||||
describe('HTTPS to HTTP using own server', function () {
|
||||
it('should proxy the request en send back the response', function (done) {
|
||||
var ports = { source: gen.port, proxy: gen.port };
|
||||
var source = http.createServer(function(req, res) {
|
||||
expect(req.method).to.eql('GET');
|
||||
expect(req.headers.host.split(':')[1]).to.eql(ports.proxy);
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.end('Hello from ' + ports.source);
|
||||
});
|
||||
|
||||
source.listen(ports.source);
|
||||
|
||||
var proxy = httpProxy.createServer({
|
||||
agent: new http.Agent({ maxSockets: 2 })
|
||||
});
|
||||
|
||||
var ownServer = https.createServer({
|
||||
key: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-key.pem')),
|
||||
cert: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-cert.pem')),
|
||||
ciphers: 'AES128-GCM-SHA256',
|
||||
}, function (req, res) {
|
||||
proxy.web(req, res, {
|
||||
target: 'http://127.0.0.1:' + ports.source
|
||||
})
|
||||
}).listen(ports.proxy);
|
||||
|
||||
https.request({
|
||||
host: 'localhost',
|
||||
port: ports.proxy,
|
||||
path: '/',
|
||||
method: 'GET',
|
||||
rejectUnauthorized: false
|
||||
}, function(res) {
|
||||
expect(res.statusCode).to.eql(200);
|
||||
|
||||
res.on('data', function (data) {
|
||||
expect(data.toString()).to.eql('Hello from ' + ports.source);
|
||||
});
|
||||
|
||||
res.on('end', function () {
|
||||
source.close();
|
||||
ownServer.close();
|
||||
done();
|
||||
})
|
||||
}).end();
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
@ -1,172 +0,0 @@
|
||||
/*
|
||||
node-http-proxy-test.js: http proxy for node.js
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Marak Squires and Fedor Indutny
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
var util = require('util'),
|
||||
assert = require('assert'),
|
||||
argv = require('optimist').argv,
|
||||
colors = require('colors'),
|
||||
request = require('request'),
|
||||
vows = require('vows'),
|
||||
websocket = require('../../vendor/websocket'),
|
||||
helpers = require('../helpers');
|
||||
|
||||
try {
|
||||
var utils = require('socket.io/lib/socket.io/utils'),
|
||||
io = require('socket.io');
|
||||
}
|
||||
catch (ex) {
|
||||
console.error('Socket.io is required for this example:');
|
||||
console.error('npm ' + 'install'.green + ' socket.io@0.6.18'.magenta);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
var options = helpers.parseProtocol(),
|
||||
testName = [options.source.protocols.ws, options.target.protocols.ws].join('-to-'),
|
||||
runner = new helpers.TestRunner(options);
|
||||
|
||||
vows.describe('node-http-proxy/http-proxy/' + testName).addBatch({
|
||||
"When using server created by httpProxy.createServer()": {
|
||||
"with no latency" : {
|
||||
"when an inbound message is sent from a WebSocket client": {
|
||||
topic: function () {
|
||||
var that = this
|
||||
headers = {};
|
||||
|
||||
runner.webSocketTest({
|
||||
io: io,
|
||||
host: 'localhost',
|
||||
wsprotocol: options.source.protocols.ws,
|
||||
protocol: options.source.protocols.http,
|
||||
ports: {
|
||||
target: 8130,
|
||||
proxy: 8131
|
||||
},
|
||||
onListen: function (socket) {
|
||||
socket.on('connection', function (client) {
|
||||
client.on('message', function (msg) {
|
||||
that.callback(null, msg, headers);
|
||||
});
|
||||
});
|
||||
},
|
||||
onWsupgrade: function (req, res) {
|
||||
headers.request = req;
|
||||
headers.response = res.headers;
|
||||
},
|
||||
onOpen: function (ws) {
|
||||
ws.send(utils.encode('from client'));
|
||||
}
|
||||
});
|
||||
},
|
||||
"the target server should receive the message": function (err, msg, headers) {
|
||||
assert.equal(msg, 'from client');
|
||||
},
|
||||
"the origin and sec-websocket-origin headers should match": function (err, msg, headers) {
|
||||
assert.isString(headers.response['sec-websocket-location']);
|
||||
assert.isTrue(headers.response['sec-websocket-location'].indexOf(options.source.protocols.ws) !== -1);
|
||||
assert.equal(headers.request.Origin, headers.response['sec-websocket-origin']);
|
||||
}
|
||||
},
|
||||
"when an inbound message is sent from a WebSocket client with event listeners": {
|
||||
topic: function () {
|
||||
var that = this
|
||||
headers = {};
|
||||
|
||||
runner.webSocketTest({
|
||||
io: io,
|
||||
host: 'localhost',
|
||||
wsprotocol: options.source.protocols.ws,
|
||||
protocol: options.source.protocols.http,
|
||||
ports: {
|
||||
target: 8132,
|
||||
proxy: 8133
|
||||
},
|
||||
onServer: function (server) {
|
||||
server.proxy.on('websocket:incoming', function (req, socket, head, data) {
|
||||
that.callback(null, data);
|
||||
});
|
||||
},
|
||||
onOpen: function (ws) {
|
||||
ws.send(utils.encode('from client'));
|
||||
}
|
||||
});
|
||||
},
|
||||
"should raise the `websocket:incoming` event": function (ign, data) {
|
||||
console.log(ign,data,utils.decode(data))
|
||||
assert.equal(utils.decode(data.toString().replace('\u0000', '')), 'from client');
|
||||
},
|
||||
},
|
||||
"when an outbound message is sent from the target server": {
|
||||
topic: function () {
|
||||
var that = this,
|
||||
headers = {};
|
||||
|
||||
runner.webSocketTest({
|
||||
io: io,
|
||||
host: 'localhost',
|
||||
wsprotocol: options.source.protocols.ws,
|
||||
protocol: options.source.protocols.http,
|
||||
ports: {
|
||||
target: 8134,
|
||||
proxy: 8135
|
||||
},
|
||||
onListen: function (socket) {
|
||||
socket.on('connection', function (client) {
|
||||
socket.broadcast('from server');
|
||||
});
|
||||
},
|
||||
onWsupgrade: function (req, res) {
|
||||
headers.request = req;
|
||||
headers.response = res.headers;
|
||||
},
|
||||
onMessage: function (msg) {
|
||||
msg = utils.decode(msg);
|
||||
if (!/\d+/.test(msg)) {
|
||||
that.callback(null, msg, headers);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
"the client should receive the message": function (err, msg, headers) {
|
||||
assert.equal(msg, 'from server');
|
||||
},
|
||||
"the origin and sec-websocket-origin headers should match": function (err, msg, headers) {
|
||||
assert.isString(headers.response['sec-websocket-location']);
|
||||
assert.isTrue(headers.response['sec-websocket-location'].indexOf(options.source.protocols.ws) !== -1);
|
||||
assert.equal(headers.request.Origin, headers.response['sec-websocket-origin']);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
"When the tests are over": {
|
||||
topic: function () {
|
||||
return runner.closeServers();
|
||||
},
|
||||
"the servers should clean up": function () {
|
||||
assert.isTrue(true);
|
||||
}
|
||||
}
|
||||
}).export(module);
|
||||
@ -1,104 +0,0 @@
|
||||
/*
|
||||
node-http-proxy-test.js: http proxy for node.js
|
||||
|
||||
Copyright (c) 2010 Charlie Robbins, Marak Squires and Fedor Indutny
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
var util = require('util'),
|
||||
assert = require('assert'),
|
||||
argv = require('optimist').argv,
|
||||
colors = require('colors'),
|
||||
request = require('request'),
|
||||
vows = require('vows'),
|
||||
websocket = require('../../vendor/websocket'),
|
||||
helpers = require('../helpers');
|
||||
|
||||
try {
|
||||
var utils = require('socket.io/lib/socket.io/utils'),
|
||||
io = require('socket.io');
|
||||
}
|
||||
catch (ex) {
|
||||
console.error('Socket.io is required for this example:');
|
||||
console.error('npm ' + 'install'.green + ' socket.io@0.6.18'.magenta);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
var options = helpers.parseProtocol(),
|
||||
testName = [options.source.protocols.ws, options.target.protocols.ws].join('-to-'),
|
||||
runner = new helpers.TestRunner(options);
|
||||
|
||||
vows.describe('node-http-proxy/routing-proxy/' + testName).addBatch({
|
||||
"When using server created by httpProxy.createServer()": {
|
||||
"using proxy table with no latency": {
|
||||
"when an inbound message is sent from a WebSocket client": {
|
||||
topic: function () {
|
||||
var that = this
|
||||
headers = {};
|
||||
|
||||
runner.webSocketTestWithTable({
|
||||
io: io,
|
||||
host: 'localhost',
|
||||
wsprotocol: options.source.protocols.ws,
|
||||
protocol: options.source.protocols.http,
|
||||
router: { 'localhost' : 'localhost:8230' },
|
||||
ports: {
|
||||
target: 8230,
|
||||
proxy: 8231
|
||||
},
|
||||
onListen: function (socket) {
|
||||
socket.on('connection', function (client) {
|
||||
client.on('message', function (msg) {
|
||||
that.callback(null, msg, headers);
|
||||
});
|
||||
});
|
||||
},
|
||||
onWsupgrade: function (req, res) {
|
||||
headers.request = req;
|
||||
headers.response = res.headers;
|
||||
},
|
||||
onOpen: function (ws) {
|
||||
ws.send(utils.encode('from client'));
|
||||
}
|
||||
});
|
||||
},
|
||||
"the target server should receive the message": function (err, msg, headers) {
|
||||
assert.equal(msg, 'from client');
|
||||
},
|
||||
"the origin and sec-websocket-origin headers should match": function (err, msg, headers) {
|
||||
assert.isString(headers.response['sec-websocket-location']);
|
||||
assert.isTrue(headers.response['sec-websocket-location'].indexOf(options.source.protocols.ws) !== -1);
|
||||
assert.equal(headers.request.Origin, headers.response['sec-websocket-origin']);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
"When the tests are over": {
|
||||
topic: function () {
|
||||
return runner.closeServers();
|
||||
},
|
||||
"the servers should clean up": function () {
|
||||
assert.isTrue(true);
|
||||
}
|
||||
}
|
||||
}).export(module);
|
||||
638
vendor/websocket.js
vendored
638
vendor/websocket.js
vendored
@ -1,638 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2010, Peter Griess <pg@std.in>
|
||||
* https://github.com/pgriess/node-websocket-client
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice,
|
||||
* this list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of node-websocket-client nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from this
|
||||
* software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
var assert = require('assert');
|
||||
var buffer = require('buffer');
|
||||
var crypto = require('crypto');
|
||||
var events = require('events');
|
||||
var http = require('http');
|
||||
var https = require('https');
|
||||
var net = require('net');
|
||||
var urllib = require('url');
|
||||
var sys = require('sys');
|
||||
|
||||
var FRAME_NO = 0;
|
||||
var FRAME_LO = 1;
|
||||
var FRAME_HI = 2;
|
||||
|
||||
// Values for readyState as per the W3C spec
|
||||
var CONNECTING = 0;
|
||||
var OPEN = 1;
|
||||
var CLOSING = 2;
|
||||
var CLOSED = 3;
|
||||
|
||||
var debugLevel = parseInt(process.env.NODE_DEBUG, 16);
|
||||
var debug = (debugLevel & 0x4) ?
|
||||
function() { sys.error.apply(this, arguments); } :
|
||||
function() { };
|
||||
|
||||
// Generate a Sec-WebSocket-* value
|
||||
var createSecretKey = function() {
|
||||
// How many spaces will we be inserting?
|
||||
var numSpaces = 1 + Math.floor(Math.random() * 12);
|
||||
assert.ok(1 <= numSpaces && numSpaces <= 12);
|
||||
|
||||
// What is the numerical value of our key?
|
||||
var keyVal = (Math.floor(
|
||||
Math.random() * (4294967295 / numSpaces)
|
||||
) * numSpaces);
|
||||
|
||||
// Our string starts with a string representation of our key
|
||||
var s = keyVal.toString();
|
||||
|
||||
// Insert 'numChars' worth of noise in the character ranges
|
||||
// [0x21, 0x2f] (14 characters) and [0x3a, 0x7e] (68 characters)
|
||||
var numChars = 1 + Math.floor(Math.random() * 12);
|
||||
assert.ok(1 <= numChars && numChars <= 12);
|
||||
|
||||
for (var i = 0; i < numChars; i++) {
|
||||
var pos = Math.floor(Math.random() * s.length + 1);
|
||||
|
||||
var c = Math.floor(Math.random() * (14 + 68));
|
||||
c = (c <= 14) ?
|
||||
String.fromCharCode(c + 0x21) :
|
||||
String.fromCharCode((c - 14) + 0x3a);
|
||||
|
||||
s = s.substring(0, pos) + c + s.substring(pos, s.length);
|
||||
}
|
||||
|
||||
// We shoudln't have any spaces in our value until we insert them
|
||||
assert.equal(s.indexOf(' '), -1);
|
||||
|
||||
// Insert 'numSpaces' worth of spaces
|
||||
for (var i = 0; i < numSpaces; i++) {
|
||||
var pos = Math.floor(Math.random() * (s.length - 1)) + 1;
|
||||
s = s.substring(0, pos) + ' ' + s.substring(pos, s.length);
|
||||
}
|
||||
|
||||
assert.notEqual(s.charAt(0), ' ');
|
||||
assert.notEqual(s.charAt(s.length), ' ');
|
||||
|
||||
return s;
|
||||
};
|
||||
|
||||
// Generate a challenge sequence
|
||||
var createChallenge = function() {
|
||||
var c = '';
|
||||
for (var i = 0; i < 8; i++) {
|
||||
c += String.fromCharCode(Math.floor(Math.random() * 255));
|
||||
}
|
||||
|
||||
return c;
|
||||
};
|
||||
|
||||
// Get the value of a secret key string
|
||||
//
|
||||
// This strips non-digit values and divides the result by the number of
|
||||
// spaces found.
|
||||
var secretKeyValue = function(sk) {
|
||||
var ns = 0;
|
||||
var v = 0;
|
||||
|
||||
for (var i = 0; i < sk.length; i++) {
|
||||
var cc = sk.charCodeAt(i);
|
||||
|
||||
if (cc == 0x20) {
|
||||
ns++;
|
||||
} else if (0x30 <= cc && cc <= 0x39) {
|
||||
v = v * 10 + cc - 0x30;
|
||||
}
|
||||
}
|
||||
|
||||
return Math.floor(v / ns);
|
||||
}
|
||||
|
||||
// Get the to-be-hashed value of a secret key string
|
||||
//
|
||||
// This takes the result of secretKeyValue() and encodes it in a big-endian
|
||||
// byte string
|
||||
var secretKeyHashValue = function(sk) {
|
||||
var skv = secretKeyValue(sk);
|
||||
|
||||
var hv = '';
|
||||
hv += String.fromCharCode((skv >> 24) & 0xff);
|
||||
hv += String.fromCharCode((skv >> 16) & 0xff);
|
||||
hv += String.fromCharCode((skv >> 8) & 0xff);
|
||||
hv += String.fromCharCode((skv >> 0) & 0xff);
|
||||
|
||||
return hv;
|
||||
};
|
||||
|
||||
// Compute the secret key signature based on two secret key strings and some
|
||||
// handshaking data.
|
||||
var computeSecretKeySignature = function(s1, s2, hs) {
|
||||
assert.equal(hs.length, 8);
|
||||
|
||||
var hash = crypto.createHash('md5');
|
||||
|
||||
hash.update(secretKeyHashValue(s1));
|
||||
hash.update(secretKeyHashValue(s2));
|
||||
hash.update(hs);
|
||||
|
||||
return hash.digest('binary');
|
||||
};
|
||||
|
||||
// Return a hex representation of the given binary string; used for debugging
|
||||
var str2hex = function(str) {
|
||||
var hexChars = [
|
||||
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
|
||||
'a', 'b', 'c', 'd', 'e', 'f'
|
||||
];
|
||||
|
||||
var out = '';
|
||||
for (var i = 0; i < str.length; i++) {
|
||||
var c = str.charCodeAt(i);
|
||||
out += hexChars[(c & 0xf0) >>> 4];
|
||||
out += hexChars[c & 0x0f];
|
||||
out += ' ';
|
||||
}
|
||||
|
||||
return out.trim();
|
||||
};
|
||||
|
||||
// Set a constant on the given object
|
||||
var setConstant = function(obj, name, value) {
|
||||
Object.defineProperty(obj, name, {
|
||||
get : function() {
|
||||
return value;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// WebSocket object
|
||||
//
|
||||
// This is intended to conform (mostly) to http://dev.w3.org/html5/websockets/
|
||||
//
|
||||
// N.B. Arguments are parsed in the anonymous function at the bottom of the
|
||||
// constructor.
|
||||
var WebSocket = function(url, proto, opts) {
|
||||
events.EventEmitter.call(this);
|
||||
|
||||
// Retain a reference to our object
|
||||
var self = this;
|
||||
|
||||
// State of our end of the connection
|
||||
var readyState = CONNECTING;
|
||||
|
||||
// Whether or not the server has sent a close handshake
|
||||
var serverClosed = false;
|
||||
|
||||
// Our underlying net.Stream instance
|
||||
var stream = undefined;
|
||||
|
||||
opts = opts || {
|
||||
origin : 'http://www.example.com'
|
||||
};
|
||||
|
||||
// Frame parsing functions
|
||||
//
|
||||
// These read data from the given buffer starting at the given offset,
|
||||
// looking for the end of the current frame. If found, the current frame is
|
||||
// emitted and the function returns. Only a single frame is processed at a
|
||||
// time.
|
||||
//
|
||||
// The number of bytes read to complete a frame is returned, which the
|
||||
// caller is to use to advance along its buffer. If 0 is returned, no
|
||||
// completed frame bytes were found, and the caller should probably enqueue
|
||||
// the buffer as a continuation of the current message. If a complete frame
|
||||
// is read, the function is responsible for resting 'frameType'.
|
||||
|
||||
// Framing data
|
||||
var frameType = FRAME_NO;
|
||||
var bufs = [];
|
||||
var bufsBytes = 0;
|
||||
|
||||
// Frame-parsing functions
|
||||
var frameFuncs = [
|
||||
// FRAME_NO
|
||||
function(buf, off) {
|
||||
if (buf[off] & 0x80) {
|
||||
frameType = FRAME_HI;
|
||||
} else {
|
||||
frameType = FRAME_LO;
|
||||
}
|
||||
|
||||
return 1;
|
||||
},
|
||||
|
||||
// FRAME_LO
|
||||
function(buf, off) {
|
||||
debug('frame_lo(' + sys.inspect(buf) + ', ' + off + ')');
|
||||
|
||||
// Find the first instance of 0xff, our terminating byte
|
||||
for (var i = off; i < buf.length && buf[i] != 0xff; i++)
|
||||
;
|
||||
|
||||
// We didn't find a terminating byte
|
||||
if (i >= buf.length) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// We found a terminating byte; collect all bytes into a single buffer
|
||||
// and emit it
|
||||
var mb = null;
|
||||
if (bufs.length == 0) {
|
||||
mb = buf.slice(off, i);
|
||||
} else {
|
||||
mb = new buffer.Buffer(bufsBytes + i);
|
||||
|
||||
var mbOff = 0;
|
||||
bufs.forEach(function(b) {
|
||||
b.copy(mb, mbOff, 0, b.length);
|
||||
mbOff += b.length;
|
||||
});
|
||||
|
||||
assert.equal(mbOff, bufsBytes);
|
||||
|
||||
// Don't call Buffer.copy() if we're coping 0 bytes. Rather
|
||||
// than being a no-op, this will trigger a range violation on
|
||||
// the destination.
|
||||
if (i > 0) {
|
||||
buf.copy(mb, mbOff, off, i);
|
||||
}
|
||||
|
||||
// We consumed all of the buffers that we'd been saving; clear
|
||||
// things out
|
||||
bufs = [];
|
||||
bufsBytes = 0;
|
||||
}
|
||||
|
||||
process.nextTick(function() {
|
||||
var b = mb;
|
||||
return function() {
|
||||
var m = b.toString('utf8');
|
||||
|
||||
self.emit('data', b);
|
||||
self.emit('message', m); // wss compat
|
||||
|
||||
if (self.onmessage) {
|
||||
self.onmessage({data: m});
|
||||
}
|
||||
};
|
||||
}());
|
||||
|
||||
frameType = FRAME_NO;
|
||||
return i - off + 1;
|
||||
},
|
||||
|
||||
// FRAME_HI
|
||||
function(buf, off) {
|
||||
debug('frame_hi(' + sys.inspect(buf) + ', ' + off + ')');
|
||||
|
||||
if (buf[off] !== 0) {
|
||||
throw new Error('High-byte framing not supported.');
|
||||
}
|
||||
|
||||
serverClosed = true;
|
||||
return 1;
|
||||
}
|
||||
];
|
||||
|
||||
// Handle data coming from our socket
|
||||
var dataListener = function(buf) {
|
||||
if (buf.length <= 0 || serverClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
debug('dataListener(' + sys.inspect(buf) + ')');
|
||||
|
||||
var off = 0;
|
||||
var consumed = 0;
|
||||
|
||||
do {
|
||||
if (frameType < 0 || frameFuncs.length <= frameType) {
|
||||
throw new Error('Unexpected frame type: ' + frameType);
|
||||
}
|
||||
|
||||
assert.equal(bufs.length === 0, bufsBytes === 0);
|
||||
assert.ok(off < buf.length);
|
||||
|
||||
consumed = frameFuncs[frameType](buf, off);
|
||||
off += consumed;
|
||||
} while (!serverClosed && consumed > 0 && off < buf.length);
|
||||
|
||||
if (serverClosed) {
|
||||
serverCloseHandler();
|
||||
}
|
||||
|
||||
if (consumed == 0) {
|
||||
bufs.push(buf.slice(off, buf.length));
|
||||
bufsBytes += buf.length - off;
|
||||
}
|
||||
};
|
||||
|
||||
// Handle incoming file descriptors
|
||||
var fdListener = function(fd) {
|
||||
self.emit('fd', fd);
|
||||
};
|
||||
|
||||
// Handle errors from any source (HTTP client, stream, etc)
|
||||
var errorListener = function(e) {
|
||||
process.nextTick(function() {
|
||||
self.emit('wserror', e);
|
||||
|
||||
if (self.onerror) {
|
||||
self.onerror(e);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Finish the closing process; destroy the socket and tell the application
|
||||
// that we've closed.
|
||||
var finishClose = function() {
|
||||
readyState = CLOSED;
|
||||
|
||||
if (stream) {
|
||||
stream.end();
|
||||
stream.destroy();
|
||||
stream = undefined;
|
||||
}
|
||||
|
||||
process.nextTick(function() {
|
||||
self.emit('close');
|
||||
if (self.onclose) {
|
||||
self.onclose();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Send a close frame to the server
|
||||
var sendClose = function() {
|
||||
assert.equal(OPEN, readyState);
|
||||
|
||||
readyState = CLOSING;
|
||||
stream.write('\xff\x00', 'binary');
|
||||
};
|
||||
|
||||
// Handle a close packet sent from the server
|
||||
var serverCloseHandler = function() {
|
||||
assert.ok(serverClosed);
|
||||
assert.ok(readyState === OPEN || readyState === CLOSING);
|
||||
|
||||
bufs = [];
|
||||
bufsBytes = 0;
|
||||
|
||||
// Handle state transitions asynchronously so that we don't change
|
||||
// readyState before the application has had a chance to process data
|
||||
// events which are already in the delivery pipeline. For example, a
|
||||
// 'data' event could be delivered with a readyState of CLOSING if we
|
||||
// received both frames in the same packet.
|
||||
process.nextTick(function() {
|
||||
if (readyState === OPEN) {
|
||||
sendClose();
|
||||
}
|
||||
|
||||
finishClose();
|
||||
});
|
||||
};
|
||||
|
||||
// External API
|
||||
self.close = function(timeout) {
|
||||
if (readyState === CONNECTING) {
|
||||
// If we're still in the process of connecting, the server is not
|
||||
// in a position to understand our close frame. Just nuke the
|
||||
// connection and call it a day.
|
||||
finishClose();
|
||||
} else if (readyState === OPEN) {
|
||||
sendClose();
|
||||
|
||||
if (timeout) {
|
||||
setTimeout(finishClose, timeout * 1000);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.send = function(str, fd) {
|
||||
if (readyState != OPEN) {
|
||||
return;
|
||||
}
|
||||
|
||||
stream.write('\x00', 'binary');
|
||||
stream.write(str, 'utf8', fd);
|
||||
stream.write('\xff', 'binary');
|
||||
};
|
||||
|
||||
// wss compat
|
||||
self.write = self.send;
|
||||
|
||||
setConstant(self, 'url', url);
|
||||
|
||||
Object.defineProperty(self, 'readyState', {
|
||||
get : function() {
|
||||
return readyState;
|
||||
}
|
||||
});
|
||||
|
||||
// Connect and perform handshaking with the server
|
||||
(function() {
|
||||
// Parse constructor arguments
|
||||
if (!url) {
|
||||
throw new Error('Url and must be specified.');
|
||||
}
|
||||
|
||||
// Secrets used for handshaking
|
||||
var key1 = createSecretKey();
|
||||
var key2 = createSecretKey();
|
||||
var challenge = createChallenge();
|
||||
|
||||
debug(
|
||||
'key1=\'' + str2hex(key1) + '\'; ' +
|
||||
'key2=\'' + str2hex(key2) + '\'; ' +
|
||||
'challenge=\'' + str2hex(challenge) + '\''
|
||||
);
|
||||
|
||||
var httpHeaders = {
|
||||
'Connection' : 'Upgrade',
|
||||
'Upgrade' : 'WebSocket',
|
||||
'Sec-WebSocket-Key1' : key1,
|
||||
'Sec-WebSocket-Key2' : key2
|
||||
};
|
||||
if (opts.origin) {
|
||||
httpHeaders['Origin'] = opts.origin;
|
||||
}
|
||||
if (proto) {
|
||||
httpHeaders['Sec-WebSocket-Protocol'] = proto;
|
||||
}
|
||||
|
||||
var httpPath = '/';
|
||||
|
||||
// Create the HTTP client that we'll use for handshaking. We'll cannabalize
|
||||
// its socket via the 'upgrade' event and leave it to rot.
|
||||
//
|
||||
// N.B. The ws+unix:// scheme makes use of the implementation detail
|
||||
// that http.Client passes its constructor arguments through,
|
||||
// un-inspected to net.Stream.connect(). The latter accepts a
|
||||
// string as its first argument to connect to a UNIX socket.
|
||||
var protocol, agent, port, u = urllib.parse(url);
|
||||
if (u.protocol === 'ws:' || u.protocol === 'wss:') {
|
||||
protocol = u.protocol === 'ws:' ? http : https;
|
||||
port = u.protocol === 'ws:' ? 80 : 443;
|
||||
agent = u.protocol === 'ws:' ? protocol.getAgent(u.hostname, u.port || port) : protocol.getAgent({
|
||||
host: u.hostname,
|
||||
port: u.port || port
|
||||
});
|
||||
|
||||
httpPath = (u.pathname || '/') + (u.search || '');
|
||||
httpHeaders.Host = u.hostname + (u.port ? (":" + u.port) : "");
|
||||
}
|
||||
else if (urlScheme === 'ws+unix') {
|
||||
throw new Error('ws+unix is not implemented');
|
||||
// var sockPath = url.substring('ws+unix://'.length, url.length);
|
||||
// httpClient = http.createClient(sockPath);
|
||||
// httpHeaders.Host = 'localhost';
|
||||
}
|
||||
else {
|
||||
throw new Error('Invalid URL scheme \'' + urlScheme + '\' specified.');
|
||||
}
|
||||
|
||||
if (!agent._events || agent._events['upgrade'].length === 0) {
|
||||
agent.on('upgrade', (function() {
|
||||
var data = undefined;
|
||||
|
||||
return function(res, s, head) {
|
||||
stream = s;
|
||||
|
||||
//
|
||||
// Emit the `wsupgrade` event to inspect the raw
|
||||
// arguments returned from the websocket request.
|
||||
//
|
||||
self.emit('wsupgrade', httpHeaders, res, s, head);
|
||||
|
||||
stream.on('data', function(d) {
|
||||
if (d.length <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
data = d;
|
||||
} else {
|
||||
var data2 = new buffer.Buffer(data.length + d.length);
|
||||
|
||||
data.copy(data2, 0, 0, data.length);
|
||||
d.copy(data2, data.length, 0, d.length);
|
||||
|
||||
data = data2;
|
||||
}
|
||||
|
||||
if (data.length >= 16) {
|
||||
var expected = computeSecretKeySignature(key1, key2, challenge);
|
||||
var actual = data.slice(0, 16).toString('binary');
|
||||
|
||||
// Handshaking fails; we're donezo
|
||||
if (actual != expected) {
|
||||
debug(
|
||||
'expected=\'' + str2hex(expected) + '\'; ' +
|
||||
'actual=\'' + str2hex(actual) + '\''
|
||||
);
|
||||
|
||||
process.nextTick(function() {
|
||||
// N.B. Emit 'wserror' here, as 'error' is a reserved word in the
|
||||
// EventEmitter world, and gets thrown.
|
||||
self.emit(
|
||||
'wserror',
|
||||
new Error('Invalid handshake from server:' +
|
||||
'expected \'' + str2hex(expected) + '\', ' +
|
||||
'actual \'' + str2hex(actual) + '\''
|
||||
)
|
||||
);
|
||||
|
||||
if (self.onerror) {
|
||||
self.onerror();
|
||||
}
|
||||
|
||||
finishClose();
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Un-register our data handler and add the one to be used
|
||||
// for the normal, non-handshaking case. If we have extra
|
||||
// data left over, manually fire off the handler on
|
||||
// whatever remains.
|
||||
//
|
||||
stream.removeAllListeners('data');
|
||||
stream.on('data', dataListener);
|
||||
|
||||
readyState = OPEN;
|
||||
|
||||
process.nextTick(function() {
|
||||
self.emit('open');
|
||||
|
||||
if (self.onopen) {
|
||||
self.onopen();
|
||||
}
|
||||
});
|
||||
|
||||
// Consume any leftover data
|
||||
if (data.length > 16) {
|
||||
stream.emit('data', data.slice(16, data.length));
|
||||
}
|
||||
}
|
||||
});
|
||||
stream.on('fd', fdListener);
|
||||
stream.on('error', errorListener);
|
||||
stream.on('close', function() {
|
||||
errorListener(new Error('Stream closed unexpectedly.'));
|
||||
});
|
||||
|
||||
stream.emit('data', head);
|
||||
};
|
||||
})());
|
||||
}
|
||||
|
||||
agent.on('error', function (e) {
|
||||
errorListener(e);
|
||||
});
|
||||
|
||||
var httpReq = protocol.request({
|
||||
host: u.hostname,
|
||||
method: 'GET',
|
||||
agent: agent,
|
||||
port: u.port,
|
||||
path: httpPath,
|
||||
headers: httpHeaders
|
||||
});
|
||||
|
||||
httpReq.write(challenge, 'binary');
|
||||
httpReq.end();
|
||||
})();
|
||||
};
|
||||
sys.inherits(WebSocket, events.EventEmitter);
|
||||
exports.WebSocket = WebSocket;
|
||||
|
||||
// Add some constants to the WebSocket object
|
||||
setConstant(WebSocket.prototype, 'CONNECTING', CONNECTING);
|
||||
setConstant(WebSocket.prototype, 'OPEN', OPEN);
|
||||
setConstant(WebSocket.prototype, 'CLOSING', CLOSING);
|
||||
setConstant(WebSocket.prototype, 'CLOSED', CLOSED);
|
||||
|
||||
// vim:ts=4 sw=4 et
|
||||
Loading…
x
Reference in New Issue
Block a user