-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker.js
57 lines (52 loc) · 1.41 KB
/
worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const { createServer } = require('http');
const https = require('https');
const http = require('http');
const config = require('./config.json');
createServer()
.on('request', (req, res) => {
if (req.headers.authorization !== config.authKey) {
res.writeHead(401, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({
status: 401,
error: 'Authorization mismatch'
}));
return;
}
let url;
let urlRaw = req.url.slice(6);
if (decodeURIComponent(urlRaw) !== urlRaw) {
urlRaw = decodeURIComponent(urlRaw);
}
try {
url = new URL(urlRaw);
} catch (e) {
res.writeHead(400, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({
status: 400,
error: urlRaw ? 'invalid URL' : 'No image URL provided'
}));
return;
}
(url.protocol === 'https:' ? https : http).get(url, (incomingRes) => {
if (incomingRes.headers['content-length']) {
res.setHeader('Content-Length', incomingRes.headers['content-length']);
}
incomingRes.pipe(res);
})
.on('error', (error) => {
res.writeHead(500, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({
status: 500,
error: error.message
}));
});
})
.listen(80, () =>
console.log('Worker', process.pid, 'launched')
);