forked from JohanPeeters/assess-webserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GetRequest.js
54 lines (52 loc) · 1.42 KB
/
GetRequest.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
51
52
53
54
const https = require('https')
const http = require('http')
const makeGetRequest = (config) => {
const {protocol, host, path, successMsg, failureMsg, expectedContent} = config
return new Promise((resolve, reject) => {
const options = {
hostname: host,
method: 'GET',
path: path,
headers: {
'Content-Type': 'application/json'
}
}
let scheme = protocol === 'http'?http:https
const req = scheme.request(options, (res) => {
res.setEncoding('utf8')
let rawData = ''
res.on('data', (chunk) => {rawData += chunk})
res.on('end', () => {
const statusCode = res.statusCode
if (statusCode == 200) {
if (expectedContent) {
if (expectedContent != rawData) {
let err = new Error(`expected at https://${host}/${path}: ${expectedContent}`)
err.actualContent = rawData
reject(err)
}
}
let body
try {
body = JSON.parse(rawData)
} catch (e) {
body = rawData
}
resolve({data: body, msg: successMsg})
} else {
let err = new Error(failureMsg)
err.statusCode = statusCode
err.rawData = rawData
reject(err)
}
})
})
req.on('error', (e) => {
reject(e)
})
req.end()
})
}
module.exports = {
makeGetRequest: makeGetRequest
}