1 | const http = require('http')
|
2 | const https = require('https')
|
3 |
|
4 | const post = async (lokiUrl, contentType, headers = {}, data = '', timeout) => {
|
5 |
|
6 | const dataBuffer = Buffer.from(data, 'utf8')
|
7 |
|
8 |
|
9 | const defaultHeaders = {
|
10 | 'Content-Type': contentType,
|
11 | 'Content-Length': dataBuffer.length
|
12 | }
|
13 |
|
14 | return new Promise((resolve, reject) => {
|
15 |
|
16 | const lib = lokiUrl.protocol === 'https:' ? https : http
|
17 |
|
18 |
|
19 | const options = {
|
20 | hostname: lokiUrl.hostname,
|
21 | port: lokiUrl.port !== '' ? lokiUrl.port : (lokiUrl.protocol === 'https:' ? 443 : 80),
|
22 | path: lokiUrl.pathname,
|
23 | method: 'POST',
|
24 | headers: Object.assign(defaultHeaders, headers),
|
25 | timeout: timeout
|
26 | }
|
27 |
|
28 |
|
29 | const req = lib.request(options, res => {
|
30 | let resData = ''
|
31 | res.on('data', _data => (resData += _data))
|
32 | res.on('end', () => resolve(resData))
|
33 | })
|
34 |
|
35 |
|
36 | req.on('error', error => {
|
37 | reject(error)
|
38 | })
|
39 |
|
40 |
|
41 | req.write(dataBuffer)
|
42 | req.end()
|
43 | })
|
44 | }
|
45 |
|
46 | module.exports = { post }
|