-
Notifications
You must be signed in to change notification settings - Fork 0
/
node-http-client.coffee
61 lines (49 loc) · 1.35 KB
/
node-http-client.coffee
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
51
52
53
54
55
56
57
58
59
60
61
url = require 'url'
http = require 'http'
get = (expected_code, url, c) ->
_request 'GET', expected_code, url, null, {}, c
get_info = (expected_code, url, c) ->
get expected_code, url, _resParsing(c)
post_info = (expected_code, url, info, c) ->
json = JSON.stringify info, null, 2
req_body = new Buffer json, 'utf8'
headers = {
'Content-Type': 'application/json'
'Content-Length': req_body.length
}
_request 'POST', expected_code, url, req_body, headers, _resParsing(c)
_resParsing = (c) ->
(e, res, body) ->
return c e, res, body if e
try
info = JSON.parse body
catch e
return c (new Error "Error decoding JSON"), res, body
c null, res, info
_request = (method, expected_code, _url, req_body, headers, c) ->
{hostname, port, path} = url.parse _url
opt = {
method
host: hostname
port: parseInt(port, 10)
path
agent: false
headers
}
req = http.request opt, (res) ->
bufs = []
res.on 'data', (data) -> bufs.push data
res.on 'end', () ->
body = Buffer.concat bufs
res.data = body
if res.statusCode != expected_code
e = new Error "Unexpected status code: #{res.statusCode}"
return c e, res
c null, res, body
if req_body
req.end req_body
else
req.end()
req.on 'error', (e) ->
c e
module.exports = {get, get_info, post_info}