Guest User

Untitled

a guest
Apr 21st, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. var http = require('http');
  2.  
  3. var nerve = exports;
  4.  
  5. nerve.serve = function(app, port, host) {
  6. function send_html(content, status_code) {
  7. this.sendHeader(status_code || 200, {"Content-Type":"text/html","Content-Length":content.length});
  8. this.sendBody(content);
  9. this.finish();
  10. }
  11.  
  12. function is_regexp(matcher) {
  13. // assuming that if the matcher has a test function, it's a regexp
  14. // what is a better way of differentiating a regexp from a regular function?
  15. return typeof matcher.test === "function";
  16. }
  17.  
  18. function request_handler(req, res) {
  19. res.send_html = send_html;
  20. for(var i = 0; i < app.length; i++) {
  21. var matcher = app[i][0], handler = app[i][1],
  22. match = req.uri.path.match(is_regexp(matcher) ? matcher : matcher.apply(req));
  23. if(match) {
  24. handler.apply(null, [req, res].concat(match.slice(1)));
  25. return;
  26. }
  27. }
  28. res.send_html('<html><head><title>Not Found</title></head><body><h1>Not Found</h1></body></html>', 404);
  29. }
  30.  
  31. http.createServer(request_handler).listen(port, host);
  32. }
  33.  
  34. get = function(regexp) {
  35. return function() { return this.method == "GET" ? regexp : false; }
  36. }
  37.  
  38. post = function(regexp) {
  39. return function() { return this.method == "POST" ? regexp : false; }
  40. }
  41.  
  42. put = function(regexp) {
  43. return function() { return this.method == "PUT" ? regexp : false; }
  44. }
  45.  
  46. del = function(regexp) {
  47. return function() { return this.method == "DELETE" ? regexp : false; }
  48. }
Add Comment
Please, Sign In to add comment