0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-01-27 22:49:56 -05:00
ghost/core/server/web/middleware/serve-public-file.js
Katharina Irrgang 7bcccc71dc
Moved apps into web folder (#9308)
refs #9178

- move express apps to one place (called `web`)
- requires https://github.com/TryGhost/Ghost-Admin/pull/923
- any further improvements are not part of this PR
- this PR just moves the files and ensures the paths are up-to-date
2017-12-06 17:37:54 +01:00

52 lines
2 KiB
JavaScript

var crypto = require('crypto'),
fs = require('fs'),
path = require('path'),
config = require('../../config'),
utils = require('../../utils');
// ### servePublicFile Middleware
// Handles requests to robots.txt and favicon.ico (and caches them)
function servePublicFile(file, type, maxAge) {
var content,
publicFilePath = config.get('paths').publicFilePath,
filePath,
blogRegex = /(\{\{blog-url\}\})/g,
apiRegex = /(\{\{api-url\}\})/g;
filePath = file.match(/^public/) ? path.join(publicFilePath, file.replace(/^public/, '')) : path.join(publicFilePath, file);
return function servePublicFile(req, res, next) {
if (req.path === '/' + file) {
if (content) {
res.writeHead(200, content.headers);
res.end(content.body);
} else {
fs.readFile(filePath, function readFile(err, buf) {
if (err) {
return next(err);
}
if (type === 'text/xsl' || type === 'text/plain' || type === 'application/javascript') {
buf = buf.toString().replace(blogRegex, utils.url.urlFor('home', true).replace(/\/$/, ''));
buf = buf.toString().replace(apiRegex, utils.url.urlFor('api', {cors: true}, true));
}
content = {
headers: {
'Content-Type': type,
'Content-Length': buf.length,
ETag: '"' + crypto.createHash('md5').update(buf, 'utf8').digest('hex') + '"',
'Cache-Control': 'public, max-age=' + maxAge
},
body: buf
};
res.writeHead(200, content.headers);
res.end(content.body);
});
}
} else {
return next();
}
};
}
module.exports = servePublicFile;