You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.4 KiB

7 years ago
  1. var fs = require('fs'),
  2. path = require('path'),
  3. union = require('../../lib'),
  4. director = require('director'),
  5. favicon = require('./middleware/favicon');
  6. var router = new director.http.Router();
  7. var server = union.createServer({
  8. before: [
  9. favicon(path.join(__dirname, 'favicon.png')),
  10. function (req, res) {
  11. var found = router.dispatch(req, res);
  12. if (!found) {
  13. res.emit('next');
  14. }
  15. }
  16. ]
  17. });
  18. router.get('/foo', function () {
  19. this.res.writeHead(200, { 'Content-Type': 'text/plain' });
  20. this.res.end('hello world\n');
  21. });
  22. router.post('/foo', { stream: true }, function () {
  23. var req = this.req,
  24. res = this.res,
  25. writeStream;
  26. writeStream = fs.createWriteStream(__dirname + '/' + Date.now() + '-foo.txt');
  27. req.pipe(writeStream);
  28. writeStream.on('close', function () {
  29. res.writeHead(200, { 'Content-Type': 'text/plain' });
  30. res.end('wrote to a stream!');
  31. });
  32. });
  33. router.get('/redirect', function () {
  34. this.res.redirect('http://www.google.com');
  35. });
  36. router.get('/custom_redirect', function () {
  37. this.res.redirect('/foo', 301);
  38. });
  39. router.get('/async', function () {
  40. var self = this;
  41. process.nextTick(function () {
  42. self.req.on('end', function () {
  43. self.res.end();
  44. })
  45. self.req.buffer = false;
  46. });
  47. });
  48. server.listen(9090);
  49. console.log('union with director running on 9090');