server.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. var fs = require('fs')
  2. , http = require('http')
  3. , path = require('path')
  4. , https = require('https')
  5. , events = require('events')
  6. , stream = require('stream')
  7. , assert = require('assert')
  8. ;
  9. exports.createServer = function (port) {
  10. port = port || 6767
  11. var s = http.createServer(function (req, resp) {
  12. s.emit(req.url, req, resp);
  13. })
  14. s.port = port
  15. s.url = 'http://localhost:'+port
  16. return s;
  17. }
  18. exports.createSSLServer = function(port, opts) {
  19. port = port || 16767
  20. var options = { 'key' : path.join(__dirname, 'ssl', 'test.key')
  21. , 'cert': path.join(__dirname, 'ssl', 'test.crt')
  22. }
  23. if (opts) {
  24. for (var i in opts) options[i] = opts[i]
  25. }
  26. for (var i in options) {
  27. options[i] = fs.readFileSync(options[i])
  28. }
  29. var s = https.createServer(options, function (req, resp) {
  30. s.emit(req.url, req, resp);
  31. })
  32. s.port = port
  33. s.url = 'https://localhost:'+port
  34. return s;
  35. }
  36. exports.createPostStream = function (text) {
  37. var postStream = new stream.Stream();
  38. postStream.writeable = true;
  39. postStream.readable = true;
  40. setTimeout(function () {postStream.emit('data', new Buffer(text)); postStream.emit('end')}, 0);
  41. return postStream;
  42. }
  43. exports.createPostValidator = function (text, reqContentType) {
  44. var l = function (req, resp) {
  45. var r = '';
  46. req.on('data', function (chunk) {r += chunk})
  47. req.on('end', function () {
  48. if (req.headers['content-type'] && req.headers['content-type'].indexOf('boundary=') >= 0) {
  49. var boundary = req.headers['content-type'].split('boundary=')[1];
  50. text = text.replace(/__BOUNDARY__/g, boundary);
  51. }
  52. if (r !== text) console.log(r, text);
  53. assert.equal(r, text)
  54. if (reqContentType) {
  55. assert.ok(req.headers['content-type'])
  56. assert.ok(~req.headers['content-type'].indexOf(reqContentType))
  57. }
  58. resp.writeHead(200, {'content-type':'text/plain'})
  59. resp.write('OK')
  60. resp.end()
  61. })
  62. }
  63. return l;
  64. }
  65. exports.createGetResponse = function (text, contentType) {
  66. var l = function (req, resp) {
  67. contentType = contentType || 'text/plain'
  68. resp.writeHead(200, {'content-type':contentType})
  69. resp.write(text)
  70. resp.end()
  71. }
  72. return l;
  73. }
  74. exports.createChunkResponse = function (chunks, contentType) {
  75. var l = function (req, resp) {
  76. contentType = contentType || 'text/plain'
  77. resp.writeHead(200, {'content-type':contentType})
  78. chunks.forEach(function (chunk) {
  79. resp.write(chunk)
  80. })
  81. resp.end()
  82. }
  83. return l;
  84. }