-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
144 lines (123 loc) · 4.42 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
const path = require('path')
const fastCgi = require('fastcgi-client')
const defaultOptions = {
host: '127.0.0.1',
port: 9000,
documentRoot: path.dirname(require.main.filename || '.'),
skipCheckServer: true
}
module.exports = function (userOptions = {}, customParams = {}) {
const options = Object.assign({}, defaultOptions, userOptions)
const fpm = new Promise((resolve, reject) => {
const loader = fastCgi(options)
loader.on('ready', () => resolve(loader))
loader.on('error', reject)
})
return async function (req, res) {
let params = Object.assign({}, customParams, {
uri: req.url
})
if (!params.uri || !params.uri.startsWith('/')) {
throw new Error('invalid uri')
}
if (options.rewrite) {
const rules = Array.isArray(options.rewrite)
? options.rewrite : [options.rewrite]
for (const rule of rules) {
const match = params.uri.match(rule.search || /.*/)
if (match) {
let result = rule.replace
for (const index in match) {
const selector = new RegExp(`\\$${index}`, 'g')
result = result.replace(selector, match[index])
}
params.outerUri = params.uri
params.uri = result
break
}
}
}
if (params.uri.indexOf('?') !== -1) {
params.document = params.uri.split('?')[0]
params.query = params.uri
.slice(params.document.length + 1)
.replace(/\?/g, '&')
}
if (!params.script) {
params.script = path.posix.join(options.documentRoot, params.document || params.uri)
}
const headers = {
REQUEST_METHOD: req.method,
CONTENT_TYPE: req.headers['content-type'],
CONTENT_LENGTH: req.headers['content-length'],
CONTENT_DISPOSITION: req.headers['content-disposition'],
DOCUMENT_ROOT: options.documentRoot,
SCRIPT_FILENAME: params.script,
SCRIPT_NAME: params.script.split('/').pop(),
REQUEST_URI: params.outerUri || params.uri,
DOCUMENT_URI: params.document || params.uri,
QUERY_STRING: params.query,
REQUEST_SCHEME: req.protocol,
HTTPS: req.protocol === 'https' ? 'on' : undefined,
REMOTE_ADDR: req.connection.remoteAddress,
REMOTE_PORT: req.connection.remotePort,
SERVER_NAME: req.connection.domain,
SERVER_PROTOCOL: 'HTTP/1.1',
GATEWAY_INTERFACE: 'CGI/1.1',
SERVER_SOFTWARE: 'php-fpm for Node',
REDIRECT_STATUS: 200
}
for (const header in headers) {
if (typeof headers[header] === 'undefined') { delete headers[header] }
}
for (header in req.headers) {
headers['HTTP_' + header.toUpperCase().replace(/-/g, '_')] = req.headers[header];
}
if (options.debug) {
console.log(headers)
}
const php = await fpm
return new Promise(function (resolve, reject) {
php.request(headers, function (err, request) {
if (err) { return reject(err) }
var output = ''
var errors = ''
req.pipe(request.stdin)
request.stdout.on('data', function (data) {
output += data.toString('utf8')
})
request.stderr.on('data', function (data) {
errors += data.toString('utf8')
})
request.stdout.on('end', function () {
if (errors) { return reject(new Error(errors)) }
const head = output.match(/^[\s\S]*?\r\n\r\n/)[0]
const parseHead = head.split('\r\n').filter(_ => _)
const responseHeaders = {}
let statusCode = 200
let statusMessage = ''
for (const item of parseHead) {
const pair = item.split(': ')
if (pair.length > 1 && pair[0] && pair[1]) {
if (pair[0] in responseHeaders) {
responseHeaders[pair[0]].push(pair[1])
} else {
responseHeaders[pair[0]] = [ pair[1] ]
}
if (pair[0] === 'Status') {
const match = pair[1].match(/(\d+) (.*)/)
statusCode = parseInt(match[1])
statusMessage = match[2]
}
}
}
res.writeHead(statusCode, statusMessage, responseHeaders)
const body = output.slice(head.length)
res.write(body)
res.end()
resolve({ headers, body })
})
})
})
}
}