Created
October 28, 2010 00:39
-
-
Save hns/650333 to your computer and use it in GitHub Desktop.
A minimal RingoJS HTTP proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var httpclient = require("ringo/httpclient"); | |
var {Headers} = require("ringo/webapp/util"); | |
var {startsWith} = require("ringo/utils/strings"); | |
var base = "http://localhost:8080"; | |
var sites = { | |
"frau.helma.at": "/frauhelma", | |
"pool.helma.at": "/pool", | |
"henso.com": "/henso", | |
"subkontent.at": { | |
"/static": "/frauhelma", | |
"/": "/frauhelma/subkontent" | |
}, | |
"murmel-comics.org": { | |
"/static": "/frauhelma", | |
"/": "/frauhelma/murmel" | |
}, | |
"plastikmaedchen.net": { | |
"/static": "/frauhelma", | |
"/": "/frauhelma/plastikmaedchen" | |
}, | |
}; | |
exports.app = function (req) { | |
var headers = Headers(req.headers); | |
var host = headers.get("host") || ""; | |
for (var vhost in sites) { | |
if (host.indexOf(vhost) > -1) { | |
var def = sites[vhost]; | |
if (typeof def === "string") { | |
return proxy(req, base + def); | |
} else { | |
for (var path in def) { | |
if (startsWith(req.pathInfo, path)) { | |
return proxy(req, base + def[path]); | |
} | |
} | |
} | |
} | |
} | |
throw {notfound: true}; | |
}; | |
exports.middleware = [ | |
"ringo/middleware/notfound", | |
"ringo/middleware/error" | |
]; | |
var client = client || new httpclient.Client(30000, false); | |
function proxy(req, url) { | |
url += req.pathInfo; | |
if (req.queryString) { | |
url += "?" + req.queryString; | |
} | |
var headers = Headers(req.headers); | |
var host = headers.get("Host"); | |
headers.unset("Host"); | |
var param = { | |
url: url, | |
method: req.method, | |
headers: headers, | |
binary: true | |
}; | |
if (req.method === "POST" || req.method === "PUT") { | |
param.data = req.input; | |
param.contentType = headers.get("Content-Type"); | |
} | |
var res = client.request(param); | |
if (res.status == 0) { | |
throw new Error("Connection failed"); | |
} | |
var location = Headers(res.headers).get("location"); | |
if (location && location.indexOf("://") > -1 && host) { | |
res.headers.set("Location", location.replace("localhost:8080", host)); | |
} | |
return { | |
status: res.status, | |
headers: res.headers, | |
body: [res.contentBytes] | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment