-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathindex.js
61 lines (54 loc) · 1.86 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const http = require('http');
const url = require('url');
const AmpOptimizer = require('@ampproject/toolbox-optimizer');
const {parseRequest, getStaticOptions} = require('./utils');
const {managementServer} = require('./metrics');
const configuration = getStaticOptions();
const ampOptimizer = AmpOptimizer.create(configuration);
process.on('SIGINT', function () {
process.exit();
});
const server = http.createServer(async (req, res) => {
const isRootRequest = url.parse(req.url).pathname === '/';
const isPost = req.method === 'POST';
if (!isPost) {
res.writeHead(400);
res.end('Error: Invalid request. This server only accepts POST requests.');
return;
}
if (!isRootRequest) {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end("Error: Invalid request. This server only accepts requests made to '/'.");
return;
}
const {body: originalHtml, query: opts} = await parseRequest(req);
if (!originalHtml) {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end('Error: Invalid request. This server requires HTML in the request body.');
return;
}
try {
const optimizedHtml = await ampOptimizer.transformHtml(originalHtml, opts);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(optimizedHtml);
} catch (err) {
console.error(err);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('500: Internal Service Error.');
}
});
const port = 3000;
if (process.env.NODE_ENV !== 'test') {
server.listen(port);
console.log(`AMP Optimizer listening at http://localhost:${port}`);
if (configuration.profile) {
const managementPort = 3001;
console.log(`Metrics are available at http://localhost:${managementPort}/metrics`);
managementServer.listen(managementPort);
}
} else {
module.exports = {
start: () => server.listen(port),
stop: () => server.close(),
};
}