index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. var ClientRequest = require('./lib/request')
  2. var response = require('./lib/response')
  3. var extend = require('xtend')
  4. var statusCodes = require('builtin-status-codes')
  5. var url = require('url')
  6. var http = exports
  7. http.request = function (opts, cb) {
  8. if (typeof opts === 'string')
  9. opts = url.parse(opts)
  10. else
  11. opts = extend(opts)
  12. // Normally, the page is loaded from http or https, so not specifying a protocol
  13. // will result in a (valid) protocol-relative url. However, this won't work if
  14. // the protocol is something else, like 'file:'
  15. var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
  16. var protocol = opts.protocol || defaultProtocol
  17. var host = opts.hostname || opts.host
  18. var port = opts.port
  19. var path = opts.path || '/'
  20. // Necessary for IPv6 addresses
  21. if (host && host.indexOf(':') !== -1)
  22. host = '[' + host + ']'
  23. // This may be a relative url. The browser should always be able to interpret it correctly.
  24. opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
  25. opts.method = (opts.method || 'GET').toUpperCase()
  26. opts.headers = opts.headers || {}
  27. // Also valid opts.auth, opts.mode
  28. var req = new ClientRequest(opts)
  29. if (cb)
  30. req.on('response', cb)
  31. return req
  32. }
  33. http.get = function get (opts, cb) {
  34. var req = http.request(opts, cb)
  35. req.end()
  36. return req
  37. }
  38. http.ClientRequest = ClientRequest
  39. http.IncomingMessage = response.IncomingMessage
  40. http.Agent = function () {}
  41. http.Agent.defaultMaxSockets = 4
  42. http.globalAgent = new http.Agent()
  43. http.STATUS_CODES = statusCodes
  44. http.METHODS = [
  45. 'CHECKOUT',
  46. 'CONNECT',
  47. 'COPY',
  48. 'DELETE',
  49. 'GET',
  50. 'HEAD',
  51. 'LOCK',
  52. 'M-SEARCH',
  53. 'MERGE',
  54. 'MKACTIVITY',
  55. 'MKCOL',
  56. 'MOVE',
  57. 'NOTIFY',
  58. 'OPTIONS',
  59. 'PATCH',
  60. 'POST',
  61. 'PROPFIND',
  62. 'PROPPATCH',
  63. 'PURGE',
  64. 'PUT',
  65. 'REPORT',
  66. 'SEARCH',
  67. 'SUBSCRIBE',
  68. 'TRACE',
  69. 'UNLOCK',
  70. 'UNSUBSCRIBE'
  71. ]