const http = require('http');
// Create an HTTP server that sends trailers
const server = http.createServer((req, res) => {
// Inform the client we'll be sending trailers
res.writeHead(200, {
'Content-Type': 'text/plain',
'Transfer-Encoding': 'chunked', // Required for trailers
'Trailer': 'Content-MD5, X-Response-Time' // Declare which trailers will be sent
});
// Write some response data
res.write('Beginning of the response\n');
// Simulate processing time
setTimeout(() => {
res.write('Middle of the response\n');
setTimeout(() => {
// Final part of the body
res.write('End of the response\n');
// Add trailers
res.addTrailers({
'Content-MD5': 'e4e68fb7bd0e697a0ae8f1bb342846d3', // Would normally be the hash of the body
'X-Response-Time': `${Date.now() - req.start}ms` // Processing time
});
// End the response
res.end();
}, 500);
}, 500);
});
// Track request start time
server.on('request', (req) => {
req.start = Date.now();
});
// Start server
const PORT = 8080;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
// Make a request to test trailers
http.get(`http://localhost:${PORT}`, (res) => {
console.log('Response status:', res.statusCode);
console.log('Response headers:', res.headers);
// Check if trailers are declared
if (res.headers.trailer) {
console.log('Trailer headers declared:', res.headers.trailer);
}
// Read the response body
let body = '';
res.on('data', (chunk) => {
body += chunk;
console.log('Received chunk:', chunk.toString());
});
// The 'end' event is emitted when the entire body has been received
res.on('end', () => {
console.log('Complete response body:', body);
console.log('Trailers received:', res.trailers);
// Server should close after test is complete
server.close();
});
}).on('error', (err) => {
console.error('Request error:', err);
});
});