forked from Raynos/http-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vhost.js
38 lines (31 loc) · 1.04 KB
/
vhost.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
// heavily based on https://github.com/senchalabs/connect/blob/master/lib/middleware/vhost.js
module.exports = vhost
// this should be a module on npm!
function vhost(hosts) {
var pairs = Object.keys(hosts).map(function (hostName) {
var handler = hosts[hostName]
var regexp = new RegExp("^" + hostName
.replace(/[^*\w]/g, "\\$&")
.replace(/[*]/g, "(?:.*?)") + "$", "i")
return [regexp, handler]
})
return function (req, res, opts, cb) {
if (!req.headers.host) {
return cb(new Error("no host header found"))
}
var host = req.headers.host.split(":")[0]
var handled = pairs.some(function (pair) {
var regexp = pair[0]
var handler = pair[1]
var match = regexp.test(host)
if (!match) {
return false
}
handler(req, res)
return true
})
if (!handled) {
return cb(new Error("could not find a vhost redirect match"))
}
}
}