index.js 1.7 KB

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