site_file.js 744 B

1234567891011121314151617181920212223242526272829
  1. 'use strict';
  2. const path = require('path');
  3. module.exports = options => {
  4. return function siteFile(ctx, next) {
  5. if (ctx.method !== 'HEAD' && ctx.method !== 'GET') return next();
  6. /* istanbul ignore if */
  7. if (ctx.path[0] !== '/') return next();
  8. const content = options[ctx.path];
  9. if (!content) return next();
  10. // '/favicon.ico': 'https://eggjs.org/favicon.ico',
  11. // content is url
  12. if (typeof content === 'string') return ctx.redirect(content);
  13. // '/robots.txt': Buffer <xx..
  14. // content is buffer
  15. if (Buffer.isBuffer(content)) {
  16. ctx.set('cache-control', options.cacheControl);
  17. ctx.body = content;
  18. ctx.type = path.extname(ctx.path);
  19. return;
  20. }
  21. return next();
  22. };
  23. };