Created
June 11, 2014 14:53
-
-
Save naosim/dc17ff74880e93002b78 to your computer and use it in GitHub Desktop.
expressっぽくうごくやつ
This file contains 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 URLMacher = (function() { | |
function URLMacher() { | |
this.map = {}; | |
} | |
URLMacher.prototype.put = function(str, obj) { | |
this.map[str] = obj; | |
}; | |
URLMacher.prototype.get = function(url) { | |
for(var key in this.map) { | |
if(url.indexOf(key) != -1) return this.map[key]; | |
} | |
return null; | |
}; | |
return URLMacher; | |
})(); | |
var MatchExecuter = (function() { | |
function MatchExecuter() { | |
this.macher = new URLMacher(); | |
} | |
MatchExecuter.prototype.put = function(method, action) { | |
this.macher.put(method, action); | |
}; | |
MatchExecuter.prototype.execute = function(url, params, resAction) { | |
var req = {"params": params}; | |
var res = {"send": resAction}; | |
var action = this.macher.get(url); | |
action(req, res); | |
}; | |
return MatchExecuter; | |
})(); | |
var ServerApplication = (function() { | |
function ServerApplication() { | |
this.getMethod = new MatchExecuter(); | |
this.postMethod = new MatchExecuter(); | |
} | |
ServerApplication.prototype.get = function(method, action) { | |
this.getMethod.put(method, action); | |
}; | |
ServerApplication.prototype.post = function(method, action) { | |
this.postMethod.put(method, action); | |
}; | |
ServerApplication.prototype.requestGet = function(url, params, resAction) { | |
this.getMethod.execute(url, params, resAction); | |
}; | |
ServerApplication.prototype.requestPost = function(url, params, resAction) { | |
this.postMethod.execute(url, params, resAction); | |
}; | |
return ServerApplication; | |
})(); | |
// nodeのexpressっぽく書く | |
var app = new ServerApplication(); | |
app.get("list", function(req, res) { | |
res.send(req.params.a); | |
}); | |
app.post("list2", function(req, res) { | |
res.send("OK2"); | |
}); | |
// ポストする側 | |
app.requestGet("http://www.yahoo.co.jp/list", {"a":3}, function(res) { | |
console.log(res);//3 | |
}); | |
app.requestPost("http://www.yahoo.co.jp/list2", null, function(res) { | |
console.log(res);//ok | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment