-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (41 loc) · 1.27 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var http = require('http')
var duplexify = require('duplexify')
var https = require('https')
var url = require('url')
module.exports = function (transport) {
var u = url.parse(transport)
var protocolName = u.protocol.slice(0, -1)
if (protocolName === 'http') return request(http, u)
if (protocolName === 'https') return request(https, u)
throw new Error('Unsupported protocol.')
}
function request (mod, u) {
var stream = duplexify()
var headers = {}
if (u.auth) headers.Authorization = 'Basic ' + new Buffer(u.auth).toString('base64')
var req = mod.request({
method: 'POST',
path: u.path,
port: u.port,
host: u.hostname,
headers: headers
})
if (!req._header && req._implicitHeader) req._implicitHeader()
if (req._send) req._send(new Buffer(0))
stream.setWritable(req)
req.on('socket', function (socket) {
// http://neophob.com/2013/09/rpc-calls-and-mysterious-40ms-delay/
socket.setNoDelay()
})
req.on('response', function (res) {
if (!/2\d\d/.test(res.statusCode)) return stream.destroy(error(res))
stream.setReadable(res)
})
return stream
}
var error = function (res) {
var err = new Error('Request failed with status ' + res.statusCode)
err.status = res.statusCode
err.headers = res.headers
return err
}